现实世界的异步和等待代码示例

3

我已经到处寻找.net 4.5中新的Async和Await特性的好的实际示例。我想出了以下代码,用于下载文件列表并限制并发下载数量。如果有最佳实践或提高/优化此代码的方法,我将不胜感激。

我们使用以下语句调用下面的代码。

await this.asyncDownloadManager.DownloadFiles(this.applicationShellViewModel.StartupAudioFiles, this.applicationShellViewModel.SecurityCookie, securityCookieDomain).ConfigureAwait(false);

我们随后使用事件将下载的文件添加到ViewModel中的ObservableCollection(.net 4.5中的新线程安全版本)。
public class AsyncDownloadManager
    {
        public event EventHandler<DownloadedEventArgs> FileDownloaded;

        public async Task DownloadFiles(string[] fileIds, string securityCookieString, string securityCookieDomain)
          {
            List<Task> allTasks = new List<Task>();
            //Limits Concurrent Downloads 
            SemaphoreSlim throttler = new SemaphoreSlim(initialCount: Properties.Settings.Default.maxConcurrentDownloads);

            var urls = CreateUrls(fileIds);

            foreach (var url in urls)   
            {  
                await throttler.WaitAsync();
                allTasks.Add(Task.Run(async () => 
                {
                    try
                    {
                        HttpClientHandler httpClientHandler = new HttpClientHandler();
                        if (!string.IsNullOrEmpty(securityCookieString))
                        {
                            Cookie securityCookie;
                            securityCookie = new Cookie(FormsAuthentication.FormsCookieName, securityCookieString);
                            securityCookie.Domain = securityCookieDomain;
                            httpClientHandler.CookieContainer.Add(securityCookie);    
                        }                     

                        await DownloadFile(url, httpClientHandler).ConfigureAwait(false);
                    }
                    finally
                    {
                        throttler.Release();
                    }
                }));
            }
            await Task.WhenAll(allTasks).ConfigureAwait(false);
        }

        async Task DownloadFile(string url, HttpClientHandler clientHandler)
        {
            HttpClient client = new HttpClient(clientHandler);
            DownloadedFile downloadedFile = new DownloadedFile();

            try
            {
                HttpResponseMessage responseMessage = await client.GetAsync(url).ConfigureAwait(false);
                var byteArray = await responseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                if (responseMessage.Content.Headers.ContentDisposition != null)
                {
                    downloadedFile.FileName = Path.Combine(Properties.Settings.Default.workingDirectory, responseMessage.Content.Headers.ContentDisposition.FileName);
                }
                else
                {
                    return;
                }

                if (!Directory.Exists(Properties.Settings.Default.workingDirectory))   
                {
                    Directory.CreateDirectory(Properties.Settings.Default.workingDirectory);
                }
                using (FileStream filestream = new FileStream(downloadedFile.FileName, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
                {
                    await filestream.WriteAsync(byteArray, 0, byteArray.Length);
                }
            }
            catch(Exception ex)
            {    
                return; 
            }
            OnFileDownloaded(downloadedFile);
        }

        private void OnFileDownloaded(DownloadedFile downloadedFile)
        {    
            if (this.FileDownloaded != null)
            {
                this.FileDownloaded(this, new DownloadedEventArgs(downloadedFile));
            }
        }    

    public class DownloadedEventArgs : EventArgs
    {
        public DownloadedEventArgs(DownloadedFile downloadedFile)
        {   
            DownloadedFile = downloadedFile;
        }

        public DownloadedFile DownloadedFile { get; set; }
    }

在Svick的建议下,以下是直接问题:

  1. 将Async / Await嵌入其他Async / Await方法会产生什么影响?(在Async / Await方法中写入文件流到磁盘)
  2. 每个单独的任务都应该使用一个httpclient还是它们应该共享一个?
  3. 事件是否是将下载文件引用“发送”到视图模型的好方法? [我也会在codereview发布]

1
我在你的帖子中没有看到任何真正的问题,所以我认为这不是这里讨论的主题。也许http://codereview.stackexchange.com/会是一个更好的选择。 - svick
现在已经重新发布在http://codereview.stackexchange.com/questions/18519/real-world-async-and-await-code-example。 - svick
2个回答

2
如果您嵌入 async/await,应该使用:
Task.ConfigureAwait(false)

对于返回Task的任何内容,都应该使用ConfigureAwait(false),否则任务将继续在调用者的线程上下文中执行,除非在UI线程上。总之,库应该使用ConfigureAwait(false),而UI代码不应该使用。就是这样!


0

我认为你的问题与你的代码没有直接关系,所以我会在这里回答它们:

将 Async / Await 嵌入其他 Async / Await 方法的效果是什么?(在 Async / Await 方法中将 filestream 写入磁盘。)

async 方法旨在像这样组合。实际上,这是 async-await 可以用来做的唯一事情:组合异步方法以创建另一个异步方法。

发生的情况是,如果您等待尚未完成的 Task,则您的方法实际上会返回给调用者。然后,当 Task 完成时,您的方法会在原始上下文(例如 UI 应用程序中的 UI 线程)上恢复。

如果您不想继续使用原始上下文(因为您不需要它),则可以使用 ConfigureAwait(false) 进行更改,就像您已经做的那样。在 Task.Run() 中执行此操作没有必要,因为该代码不在原始上下文中运行。

每个单独的任务都应该使用一个 httpclient 还是它们应该共享一个?

HttpClient 的文档说明其实例方法不是线程安全的,因此您应该为每个 Task 使用单独的实例。

事件是否是将下载文件引用“发送”到视图模型的好方法?

我认为事件与 async-await 不太搭配。在您的情况下,只有在您使用 BindingOperations.EnableCollectionSynchronization 并且在自己的代码中正确锁定集合时,它才能正常工作。

我认为更好的选择是使用类似 TPL Dataflow 或 Rx 的东西。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接