运行 两个任务与 GUI 更新并行

Running two tasks in parallel with GUI update

我已经下载了 C#async/await 的示例代码

https://code.msdn.microsoft.com/Async-Sample-Example-from-9b9f505c

现在我尝试调整它以实现不同的目标:我想在执行 GetStringAsync

时更新 GUI

这就是我所做的并且它有效,但我对我的代码有一些疑问。如果它是正确的或 "right" 方法。

1- 使用Task.WhenAll 来运行 两个并行任务

2- 每 200 毫秒向等待文本附加一个点的任务方法 UpdateUIAsync 应该使用 dispatcher.begininvoke 完成还是这种方式可以?

3- 再次分享使用字段 finished 来同步行为,"ok" 还是有更好的方法?

public partial class MainWindow : Window
{
    // Mark the event handler with async so you can use await in it.
    private async void StartButton_Click(object sender, RoutedEventArgs e)
    {
        // Call and await separately.
        //Task<int> getLengthTask = AccessTheWebAsync();
        //// You can do independent work here.
        //int contentLength = await getLengthTask;
        finished = false;
        int[] contentLength = await Task.WhenAll(AccessTheWebAsync(), UpdateUIAsync());

        resultsTextBox.Text +=
            String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength[0]);
    }

    bool finished = false;

    // Three things to note in the signature:
    //  - The method has an async modifier. 
    //  - The return type is Task or Task<T>. (See "Return Types" section.)
    //    Here, it is Task<int> because the return statement returns an integer.
    //  - The method name ends in "Async."

    async Task<int> UpdateUIAsync()
    {
        resultsTextBox.Text = "Working ";
        while (!finished)
        {
            resultsTextBox.Text += ".";
            await Task.Delay(200);
        }
        resultsTextBox.Text += "\r\n";

        //Task<int> write = new Task<int>(() =>
        //{
        //    Dispatcher.BeginInvoke((Action)(() =>
        //    {
        //        resultsTextBox.Text = "Working ";
        //        while (!finished)
        //        {
        //            resultsTextBox.Text += ".";
        //            Task.Delay(200);
        //        }
        //        resultsTextBox.Text += "\r\n";
        //    }));

        //    return 1;
        //});

        return 1;
    }
    async Task<int> AccessTheWebAsync()
    {
        // You need to add a reference to System.Net.Http to declare client.
        HttpClient client = new HttpClient();

        // GetStringAsync returns a Task<string>. That means that when you await the
        // task you'll get a string (urlContents).
        Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

        // The await operator suspends AccessTheWebAsync.
        //  - AccessTheWebAsync can't continue until getStringTask is complete.
        //  - Meanwhile, control returns to the caller of AccessTheWebAsync.
        //  - Control resumes here when getStringTask is complete. 
        //  - The await operator then retrieves the string result from getStringTask.
        string urlContents = await getStringTask;
        finished = true;
        // The return statement specifies an integer result.
        // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
        return urlContents.Length;
    }
}

async-await 报告进度的方式是通过 IProgress Interface and it's implementation, the Progress Class

如果您将 UpdateUIAsync 方法更改为:

private async Task UpdateUIAsync(IProgress<string> progress, CancellationToken cancellationToken)
{
    while (!cancellationToken.IsCancellationRequested)
    {
        progress.Report(".");
        await Task.Delay(200);
    }
}

那么你可以这样使用它:

private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    this.resultsTextBox.Text = "Working ";

    using (var cts = new CancellationTokenSource())
    {
        var task = AccessTheWebAsync();
        await Task.WhenAny(
            task, 
            UpdateUIAsync(
                new Progress<string>(s => this.resultsTextBox += s),
                cts.Token));
        cts.Cancel();
        var contentLength = await task;
    }

    this.resultsTextBox.Text +=
        String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
}

1- Using Task.WhenAll to run two Task in parallel

操作运行宁并发Task.WhenAll是异步并发的合适机制。您的所有代码 运行 仅在一个线程上,因此这里没有真正的并行性。

2- Should the Task Method UpdateUIAsync that appends a dot every 200ms to the waiting text be done with the dispatcher.begininvoke or is this way ok?

Dispatcher 不是必需的,因为代码 运行s 在 UI 线程上。但是,我确实推荐 IProgress<T> 模式 ,因为这有助于使您的代码更易于测试,并减少对特定 UI.

的依赖

3- Share use of field finished to synchronize behaviours, again, "ok" or is there a better approach?

不受保护的共享字段在这种情况下确实有效,因为您的所有代码都在单个线程上 运行。但是,我建议使用 CancellationToken 模式,这样语义更清晰:当 AccessTheWebAsync 完成时,您的代码想要 cancel UpdateUIAsync。使用像这样的既定模式不仅可以阐明意图,还可以使代码更易于重用。