C#异步/等待关于任务和进度下活动;>目的 [英] C# async/await Progress event on Task<> object

查看:96
本文介绍了C#异步/等待关于任务和进度下活动;>目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全新的C#5新的异步 / 等待关键字和我感兴趣的最好办法实施进度的事件​​。

现在我preFER,如果一个进度事件是在任务<> 本身。我知道我可以只把事件中包含的异步方法和传递某种事件处理程序状态对象的类,但对我来说这似乎是更多的是解决办法比的解决方案。我可能还需要不同的任务来火了不同对象的事件处理程序,这听起来杂乱这种方式。

有没有一种方法,我可以做类似如下的内容:

  VAR任务= scanner.PerformScanAsync();
task.ProgressUpdate + = scanner_ProgressUpdate;
返回等待任务;


解决方案

简而言之,工作的支持进度。然而,有已经在这样做的传统方式,使用 IProgress< T> 接口。基于任务的异步模式基本上表明您超载异步方法(它是有道理的),以便客户通过在 IProgess< T> 的实施。然后,您的异步方法将通过该报告进度。

Windows运行时(WinRT的)API的确实的有进步指标内置,在<一个href=\"http://msdn.microsoft.com/en-us/library/windows/apps/br206594.aspx\"><$c$c>IAsyncOperationWithProgress<TResult, TProgress&GT; 和<一个href=\"http://msdn.microsoft.com/en-us/library/windows/apps/br206581.aspx\"><$c$c>IAsyncActionWithProgress<TProgress>类型...因此,如果你实际编写WinRT的,这些都是值得探讨 - 但是阅读以下为好意见

I'm completely new to C# 5's new async/await keywords and I'm interested in the best way to implement a progress event.

Now I'd prefer it if a Progress event was on the Task<> itself. I know I could just put the event in the class that contains the asynchronous method and pass some sort of state object in the event handler, but to me that seems like more of a workaround than a solution. I might also want different tasks to fire off event handlers in different objects, which sounds messy this way.

Is there a way I could do something similar to the following?:

var task = scanner.PerformScanAsync();
task.ProgressUpdate += scanner_ProgressUpdate;
return await task;

解决方案

Simply put, Task doesn't support progress. However, there's already a conventional way of doing this, using the IProgress<T> interface. The Task-based Asynchronous Pattern basically suggests overloading your async methods (where it makes sense) to allow clients to pass in an IProgess<T> implementation. Your async method would then report progress via that.

The Windows Runtime (WinRT) API does have progress indicators built-in, in the IAsyncOperationWithProgress<TResult, TProgress> and IAsyncActionWithProgress<TProgress> types... so if you're actually writing for WinRT, those are worth looking into - but read the comments below as well.

这篇关于C#异步/等待关于任务和进度下活动;&GT;目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆