简体   繁体   English

使用同步长时间运行的任务创建异步方法

[英]Create async method using sync long-running tasks

Maybe this is a duplicate, but I haven't seen anything similar, or not googled so much... I'm pretty new on async pattern... 也许这是重复的,但是我还没有看到任何类似的东西,或者没有在谷歌上搜索太多...我在异步模式上还很新...

Imagine that you have a long running (and thread-blocking) processing task, bound to a DLL which you don't have code access. 想象一下,您有一个长时间运行(和线程阻塞)的处理任务,绑定到您没有代码访问权限的DLL。 like this one: 像这个:

void DoSomeLongRunningTask(out int taskProgress);

I need this inside an async method on an ASP.NET MVC 4 Controller. 我需要在ASP.NET MVC 4控制器的异步方法中使用此方法。 The taskProgress out parameter will feed a progressbar-like component. taskProgress out参数将提供类似进度条的组件。

How could I enclose that synchronous method on an async method? 如何将同步方法放在异步方法上? Could you point me some direction on how do I accomplish that? 您能为我指出如何实现这一目标的方向吗?

Thank you in advance. 先感谢您。

If you need to dispatch a long running synchronous task asynchronously, and you have no access to the DLL dispatching the method to make it truely async, you can use Task.Run or in this case Task.Factory.Startnew to deploy it on a ThreadPool thread. 如果您需要异步分派长时间运行的同步任务,您必须将DLL没有进入调度方法,使其忠实地异步,您可以使用Task.Run或在这种情况下Task.Factory.Startnew给它一个线程池部署线。

var myTask = await Task.Factory.StartNew(() => DoSomeLongRunningTask(out taskProgress), TaskCreationOptions.LongRunning);

Using Task.Factory.Startnew with TaskCreationOptions.LongRunning is to signal the TaskScheduler that we will need a new dedicated Thread for the work done so we dont cause starvation to the ThreadPool Task.Factory.StartnewTaskCreationOptions.LongRunning Task.Factory.Startnew使用是为了通知TaskScheduler我们将需要一个新的专用线程来完成工作,因此我们不会对ThreadPool造成饥饿

DoSomeLongRunningTask returns a Task in this case, since the return type is void , which will be completed in the future when the method finishes. 在这种情况下, DoSomeLongRunningTask返回一个Task ,因为返回类型为void ,该方法将在以后方法完成时完成。

If you had access to that method, i would suggest you look at IProgress<T> , which exposes a simple Progress method which with you can update your UI. 如果您可以使用该方法,则建议您查看IProgress<T> ,它提供了一个简单的Progress方法,可用来更新您的UI。

Here is an example in case you want to implement progress next time, and you do have control over the async method. 这是一个示例 ,以防您下次想要实现进度并且确实可以控制async方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM