C# 异步编程示例

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Threading;

 
 

namespace ConsoleApplication3

{

class
Program

{

static
void Main(string[] args)

{

Console.WriteLine($”主程序头,当前线程ID{Thread.CurrentThread.ManagedThreadId});

CallSayHiAysnc(“Jack”);

Console.WriteLine($”主程序尾,当前线程ID{Thread.CurrentThread.ManagedThreadId});

Console.ReadKey();

}

 
 

static
async
void CallSayHiAysnc(string name)

{

Console.WriteLine($”异步调用头,当前线程ID{Thread.CurrentThread.ManagedThreadId});

string result = await SayHiAsync(name);

Console.WriteLine($”异步调用尾,当前线程ID{Thread.CurrentThread.ManagedThreadId});

Console.WriteLine(result);

}

static
Task<string> SayHiAsync(string name)

{

return
Task.Run<string>(()=> { return SayHi(name); });

}

static
string SayHi(string name)

{

Thread.Sleep(10000);

Console.WriteLine($”SayHi已执行,当前线程ID{Thread.CurrentThread.ManagedThreadId});

return
$”Hi,{name};

}

 
 

}

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注