【发布时间】:2012-11-04 03:19:47
【问题描述】:
我正在查看 codeplex 上的下载管理器类型项目并遇到了这个: http://nthdownload.codeplex.com/
浏览我在AddDownloads 等方法中运行的代码,如下所列:
AddDownloads 启动 _downloadQueue.AddDownloads 任务并继续执行 viewMaintenanceTask 任务。如果您查看这 2 个任务和下游发生的方法和事情,似乎一切都是同步的。
同时阅读这篇博文,Synchronous tasks with Task 我试图了解将同步方法包装在TaskCompletionSource 中的优势(如果有的话)。是因为它为 API 使用者提供了在单独的线程上启动任务的选项,还是仅仅因为您想将该方法用作 Task。包裹在TaskCompletionSource 中的同步方法是否受益于并行处理?
private Task<QueueOperation> AddDownloads(IEnumerable<IDownload> downloads, out Task<QueueOperation> startTask)
{
var addTask = _downloadQueue.AddDownloads(downloads, out startTask);
// Maintain views
var viewMaintenanceTask = addTask.ContinueWith(t =>
{
if (t.Exception == null)
{
var addedDownloads = t.Result.DownloadErrors.Where(k => k.Value == null).Select(k => k.Key).ToList();
var activeDownloads = ActiveDownloads.ToList();
AddToActiveDownloads(addedDownloads.Except(activeDownloads).ToList(), false);
}
else
{
// Rethrow exception, this ensures it'll bubble up to any further ContinueWith chained off this task
throw t.Exception;
}
return t.Result;
});
return viewMaintenanceTask;
}
博客文章中的示例方法,将同步操作包装在 TaskCompletionSource 中:
var tcs = new TaskCompletionSource<object>();
try
{
object result = model.Deserialize(stream, null, type);
tcs.SetResult(result);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
【问题讨论】:
标签: c# async-await