[英]Unable to debug a program that uses concurrent async / await
对这个程序的观察:
在此程序中缓慢按F11不会显示ProcessURL()
每次执行
通过该程序快速按F11键可显示更多执行的ProcessURL()
使用Thread.Sleep(3000);
ProcessURL中的结果导致MainUI线程挂起大约30秒。 没有UI重绘,并且“取消”按钮不可用。
需求:
码
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;
}
}
}
假设将对Thread.Sleep
的调用放在await
调用之前 ,则完全可以确定UI线程已锁定:您正在阻止它。 您的ProcessURL
方法将同步执行,直到您为尚未完成的操作命中第一个await
表达式为止。 当到达那里时,它将附加一个延续,然后返回。
因此,如果在等待之前进行了Thread.Sleep
调用,则在执行LINQ查询时(当您调用ToList
,您将连续调用该方法7次,每次在UI线程中休眠3秒钟。UI)将被锁定了,而这种情况发生。如果你把Thread.Sleep
后 await
,那么UI将仍然被锁定在相同的时间,但在小爆发。
Thread.Sleep
的异步等效项是使用Task.Delay
:
await Task.Delay(3000);
基本上,这会立即返回,并附加一个持续时间,它将在3秒内触发。
(我不知道有关调试的问题-我不会尝试调试到大多数那些语句的......这不是很清楚,我正是你所试图达到或为什么在断点。 ProcessURL
应该得到命中每个网址。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.