案例1

 1 public class Program
 2     {
 3         async static Task Main(string[] args)
 4         {
 5             Helper.PrintThreadId("before", "main");
 6             await FooAsync();
 7             Helper.PrintThreadId("after", "main");
 8             Console.ReadLine();
 9         }
10 
11         async static Task FooAsync()
12         {
13             //await Task.Delay(3000);
14             Helper.PrintThreadId("before", "FooAsync");
//ConfigureAwait(false) 代表执行完之后不会回到原来线程 true则为回到原来线程
15 await Task.Delay(1000).ConfigureAwait(false); 16 Helper.PrintThreadId("after", "FooAsync"); 17 } 18 } 19 20 class Helper 21 { 22 static int index = 1; 23 public static void PrintThreadId(string message = null, [CallerMemberName] string name = null) 24 { 25 var title = ""; 26 if(!string.IsNullOrEmpty(message)) 27 { 28 title = $"@{message}:{name}"; 29 } 30 Console.WriteLine(title+":"+ Environment.CurrentManagedThreadId.ToString()) ; 31 Interlocked.Increment(ref index) ; 32 } 33 }

输出结果:

@before:main:1
@before:FooAsync:1

//间隔1s ,输出下面内容
@after:FooAsync:4
@after:main:4

 

posted @ 2024-07-14 13:45  NoTimeFF  阅读(14)  评论(0)    收藏  举报