在下面的 MSDN 示例中WPF
应用程序,它演示了async/await
多异步的实现Tasks
, the Dispatcher
对象显然没有被使用/需要,即异步执行Tasks
似乎可以直接访问 UI 控件(在本例中resultTextBox
TextBox
控制 - 看线resultsTextBox.Text += String.Format("\r\nLength of the download: {0}", length);
)。该应用程序已经过测试,性能符合预期。
但是,那question仍然存在该实现是否能够正确处理可能的竞争条件,例如,如果等待并完成Task
尝试访问该TextBox
控制,而后者仍在处理先前完成的更新Task
?从实际意义上来说,is WPF Dispatcher
仍然需要对象来处理这种潜在的并发/竞争条件问题async/await
多任务执行(或者,可能是,联锁功能已以某种方式在此类异步/等待编程构造中隐式实现)?
清单 1。 MSDN 文章“启动多个异步任务并在完成时处理它们”(https://msdn.microsoft.com/en-us/library/jj155756.aspx https://msdn.microsoft.com/en-us/library/jj155756.aspx)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// Add a using directive and a reference for System.Net.Http.
using System.Net.Http;
// Add the following using directive.
using System.Threading;
namespace ProcessTasksAsTheyFinish
{
public partial class MainWindow : Window
{
// Declare a System.Threading.CancellationTokenSource.
CancellationTokenSource cts;
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();
try
{
await AccessTheWebAsync(cts.Token);
resultsTextBox.Text += "\r\nDownloads complete.";
}
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownloads failed.\r\n";
}
cts = null;
}
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
async Task AccessTheWebAsync(CancellationToken ct)
{
HttpClient client = new HttpClient();
// Make a list of web addresses.
List<string> urlList = SetUpURLList();
// ***Create a query that, when executed, returns a collection of tasks.
IEnumerable<Task<int>> downloadTasksQuery =
from url in urlList select ProcessURL(url, client, ct);
// ***Use ToList to execute the query and start the tasks.
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();
// ***Add a loop to process the tasks one at a time until none remain.
while (downloadTasks.Count > 0)
{
// Identify the first task that completes.
Task<int> firstFinishedTask = await Task.WhenAny(downloadTasks);
// ***Remove the selected task from the list so that you don't
// process it more than once.
downloadTasks.Remove(firstFinishedTask);
// Await the completed task.
int length = await firstFinishedTask;
resultsTextBox.Text += String.Format("\r\nLength of the download: {0}", length);
}
}
private List<string> SetUpURLList()
{
List<string> urls = new List<string>
{
"http://msdn.microsoft.com",
"http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
"http://msdn.microsoft.com/en-us/library/hh290136.aspx",
"http://msdn.microsoft.com/en-us/library/dd470362.aspx",
"http://msdn.microsoft.com/en-us/library/aa578028.aspx",
"http://msdn.microsoft.com/en-us/library/ms404677.aspx",
"http://msdn.microsoft.com/en-us/library/ff730837.aspx"
};
return urls;
}
async Task<int> ProcessURL(string url, HttpClient client, CancellationToken ct)
{
// GetAsync returns a Task<HttpResponseMessage>.
HttpResponseMessage response = await client.GetAsync(url, ct);
// Retrieve the website contents from the HttpResponseMessage.
byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
return urlContents.Length;
}
}
}
Note: 我想要感谢斯蒂芬·克利里感谢他出色的回答和相当有见地的解释,并且还想强调他的解决方案中概述的建议改进,即:利用替换原始 MSDN 示例中不必要/复杂的代码块WhenAny
通过封装在一行代码中的相当紧凑的解决方案,即:await Task.WhenAll(downloadTasks);
(顺便说一句,我在许多实际应用程序中使用了这种替代方案,特别是处理多个股票网络查询的在线市场数据应用程序)。
非常感谢,斯蒂芬!