Prevent winforms UI block when using async/await

后端 未结 2 970
没有蜡笔的小新
没有蜡笔的小新 2020-12-18 04:49

I\'m fairly new to async/await programming and sometimes I feel that I understand it, and then all of a sudden something happens and throws me for a loop.

I\'m tryin

相关标签:
2条回答
  • 2020-12-18 05:30

    You just need to change the DoStuffAsync task little bit, as below.

    private async Task<int> DoStuffAsync(CancellationTokenSource c)
    {
         return Task<int>.Run(()=> {
                int ret = 0;
    
                // I wanted to simulator a long running process this way
                // instead of doing Task.Delay
    
                for (int i = 0; i < 500000000; i++)
                {
    
    
    
                    ret += i;
                    if (i % 100000 == 0)
                        Console.WriteLine(i);
    
                    if (c.IsCancellationRequested)
                    {
                        return ret;
                    }
                }
                return ret;
            });
    }
    
    0 讨论(0)
  • 2020-12-18 05:31

    When you write such code:

    private async Task<int> DoStuffAsync()
    {
        return 0;
    }
    

    This way you are doing things synchronously, because you are not using await expression.

    Pay attention to the warning:

    This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

    Based on the warning suggestion you can correct it this way:

    private async Task<int> DoStuffAsync()
    {
        return await Task.Run<int>(() =>
        {
            return 0;
        });
    }
    

    To learn more about async/await you can take a look at:

    • Async and Await by Stephen Cleary
    • Asynchronous Programming with Async and Await from msdn
    0 讨论(0)
提交回复
热议问题