任务上的 C# async/await Progress 事件<>目的 [英] C# async/await Progress event on Task<> object

查看:36
本文介绍了任务上的 C# async/await Progress 事件<>目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C# 5 的新 async/await 关键字完全陌生,我对实现进度事件的最佳方式很感兴趣.

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.

现在我更喜欢 Progress 事件发生在 Task<> 本身上.我知道我可以将事件放在包含异步方法的类中,并在事件处理程序中传递某种状态对象,但在我看来,这更像是一种解决方法而不是解决方案.我可能还希望不同的任务在不同的对象中触发事件处理程序,这听起来很混乱.

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;

推荐答案

简单地说,Task 不支持进度.但是,已经有一种传统的方法可以做到这一点,使用 IProgress; 界面.基于任务的异步模式 基本上建议重载你的异步方法(它有意义)以允许客户端传入 IProgess 实现.然后,您的异步方法将通过该方法报告进度.

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.

Windows 运行时 (WinRT) API 确实具有内置的进度指示器,位于 IAsyncOperationWithProgressIAsyncActionWithProgress<TProgress> 类型...因此,如果您实际上是为 WinRT 编写代码,那么这些值得研究 -但也请阅读下面的评论.

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# async/await Progress 事件&lt;&gt;目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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