1

对该程序的观察:

  • 通过这个程序慢慢按 F11 并不显示每次执行ProcessURL()

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

  • 在 ProcessURL 中使用Thread.Sleep(3000);会导致 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;
        }
    }
}
4

1 回答 1

5

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

因此,如果您Thread.Sleep在 await 之前进行了调用,则在执行 LINQ 查询时(调用时ToList,您将连续调用该方法 7 次,每次在 UI 线程中休眠 3 秒。UI 将被锁定发生这种情况时。如果您将 放在Thread.Sleep 之后await则 UI 仍将被锁定相同的时间,但会以少量爆发。

的异步等价物Thread.Sleep是使用Task.Delay

await Task.Delay(3000);

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

(我不知道调试问题 - 我不会尝试调试大多数这些语句......我不清楚你究竟想要实现什么或为什么。每个断点都应该ProcessURL被击中网址虽然。)

于 2012-10-26T14:18:12.480 回答