我已经在C#中下载了async / await的示例代码
https://code.msdn.microsoft.com/Async-Sample-Example-from-9b9f505c
现在我尝试调整它以实现不同的目标:我想在执行GetStringAsync
时更新GUI
所以这就是我所做的并且它有效,但我对我的代码有些怀疑。如果它是正确的或“正确”的方式来做到这一点。
1-使用Task.WhenAll
并行运行两个Task
2-任务方法UpdateUIAsync
是否每隔200ms将一个点附加到等待的文本上用dispatcher.begininvoke
完成或者这样可以吗?
3-分享使用字段finished
同步行为,再次,“确定”还是有更好的方法?
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;
}
}
1-使用Task.WhenAll并行运行两个Task
这些操作同时运行,而Task.WhenAll
是异步并发的适当机制。你的所有代码只在一个线程上运行,所以这里没有真正的并行性。
2-应该使用dispatcher.begininvoke完成每隔200ms将一个点附加到等待文本的任务方法UpdateUIAsync,或者这样可以吗?
Dispatcher
不是必需的,因为代码在UI线程上运行。但是,我建议使用IProgress<T>
模式as Paulo recommended,因为这有助于使您的代码更易于测试,并且与特定UI的联系更少。
3-共享使用字段完成同步行为,再次,“确定”还是有更好的方法?
在这种情况下,未受保护的共享字段可以正常工作,因为所有代码都在单个线程上运行。但是,我建议使用CancellationToken
模式,以便语义更清晰:当AccessTheWebAsync
完成时,你的代码想要取消UpdateUIAsync
。使用已建立的模式不仅可以澄清意图,还可以使代码更具可重用性。
async-await
报告进展的方式是通过IProgress Interface和它的实施,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);
}