簡體   English   中英

使用async / await時防止winforms UI阻止

[英]Prevent winforms UI block when using async/await

我對async / await編程很新,有時候我覺得我理解它,然后突然發生了一些事情,並引發了我的循環。

我在測試winforms應用程序中嘗試這個,這是我的一個版本的片段。 這樣做會阻止UI

private async void button1_Click(object sender, EventArgs e)
{

    int d = await DoStuffAsync(c);

    Console.WriteLine(d);

}

private async Task<int> DoStuffAsync(CancellationTokenSource c)
{

        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;
}

現在,當我通過在Task.Run中包裝“DoStuffAsync()”的主體進行輕微更改時,它的工作完全正常

private async Task<int> DoStuffAsync(CancellationTokenSource c)
    {
        var t = await Task.Run<int>(() =>
        {
            int ret = 0;
            for (int i = 0; i < 500000000; i++)
            {



                ret += i;
                if (i % 100000 == 0)
                    Console.WriteLine(i);

                if (c.IsCancellationRequested)
                {
                    return ret;
                }
            }
            return ret;

        });


        return t;
    }

盡管如此,處理這種情況的正確方法是什么?

當你寫這樣的代碼時:

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

這樣你就可以同步處理,因為你沒有使用await表達式。

注意警告:

這種異步方法缺少“等待”運算符並將同步運行。 考慮使用'await'運算符等待非阻塞API調用,或'await Task.Run(...)'在后台線程上執行CPU綁定工作。

根據警告建議,您可以這樣糾正:

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

要了解有關async / await的更多信息,您可以查看:

您只需稍微更改DoStuffAsync任務,如下所示。

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;
        });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM