Tuesday, November 1, 2016

async void vs async task behave different


(1) for async-void, 2nd resume will never happen. 1st resume does happen
(2) for async-Task, both resume will not happen.

So async-void does not block Event Handler, but itself will be blocked forever
async-task Both event handler and itself will be blocked.
In both cases, UI is responsive=> There is a suspension point and UI return to do other things.
But resume gets affected

       private async void button_Click(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("thread id:{0}", Thread.CurrentThread.ManagedThreadId);
          // m();
            await mT();
            Debug.WriteLine("Resume 1");
        }

        async void m()
        {
            Debug.WriteLine("thread id:{0}", Thread.CurrentThread.ManagedThreadId);
            await Task.Run(() => {
                Debug.WriteLine("thread id:{0}",Thread.CurrentThread.ManagedThreadId);
                for (;;) { }
            });
            Debug.WriteLine("Resume 2");
        }

        async Task mT()
        {
            Debug.WriteLine("thread id:{0}", Thread.CurrentThread.ManagedThreadId);
            await Task.Run(() => {
                Debug.WriteLine("thread id:{0}", Thread.CurrentThread.ManagedThreadId);
                for (;;) { }
            });
            Debug.WriteLine("Resume 2");
        }

No comments:

Post a Comment