无法调试使用并发async/await的程序

goo*_*ate 1 .net c# debugging async-await .net-4.5

对该计划的观察:

  • 通过该程序缓慢按F11不会显示每次执行 ProcessURL()

  • 通过此程序快速按F11可显示更多的执行 ProcessURL()

  • Thread.Sleep(3000);在ProcessURL中使用会导致MainUI线程挂起大约30秒.没有UI重绘,取消按钮不可用.

需求:

  • 我想逐步完成ProcessURL的每次执行,或者使用本机Visual Studio工具或开源添加来可视化它

在此输入图像描述

可从此处下载

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

假设你在调用Thread.Sleep 之前await调用了调用,那么UI线程被锁定是完全合理的:你阻止了它.您的ProcessURL方法将同步执行,直到您找到await尚未完成的第一个表达式.当它到达那里时,它将附加一个延续然后返回.

因此,如果您Thread.Sleep在等待之前接到了调用ToList,那么当您执行LINQ查询时(当您调用时,您将连续7次调用该方法,每次在UI线程中休眠3秒.UI将被锁定而发生这种情况.如果你把Thread.Sleep 以后await,那么UI将仍然被锁定在相同的时间,但在小爆发.

异步等价Thread.Sleep于使用Task.Delay:

await Task.Delay(3000);
Run Code Online (Sandbox Code Playgroud)

这将基本上立即返回,附加一个将在3秒内触发的延续.

(我不知道有关调试的问题-我不会尝试调试最这些语句的......这不是很清楚,我正是你所试图达到或为什么在断点.ProcessURL应该获得击中每个虽然URL.)