C# async/await strange behavior in console app

前端 未结 4 854
臣服心动
臣服心动 2021-01-17 22:33

I built some async/await demo console app and get strange result. Code:

class Program
{
    public static void BeginLongIO(Action act)
    {
        Console.         


        
4条回答
  •  孤城傲影
    2021-01-17 23:12

    the line that actually runs something on a background thread is

       Task.Run( () => {  } ); 
    

    In your example you are not awaiting that Task but that of a TaskCompletionSource

       public static Task LongIOAsync()
       {
            var tcs = new TaskCompletionSource();
    
            Task.Run ( () => BeginLongIO(() =>
            {
                try { tcs.TrySetResult(EndLongIO()); }
                catch (Exception exc) { tcs.TrySetException(exc); }
            }));
    
            return tcs.Task;    
       }
    

    When awaiting LongIOAsync you are awaiting the the task from tcs witch is set from a background thread in a delegate given to Task.Run()

    apply this change :

        public static Task LongIOAsync()
        {
            Console.WriteLine("In LongIOAsync start... {0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
            var tcs = new TaskCompletionSource();
    
            Task.Run ( () => BeginLongIO(() =>
            {
                try { tcs.TrySetResult(EndLongIO()); }
                catch (Exception exc) { tcs.TrySetException(exc); }
            }));
    
            Console.WriteLine("In LongIOAsync end... \t{0} {1}", (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, Thread.CurrentThread.ManagedThreadId);
            return tcs.Task;
        }
    

    Alternately in this case you could of just awaited the returned from Task.Run() , TaskCompletionSource is for situations where you want to pass around the ability to set your Task as complete or other wise.

提交回复
热议问题