简体   繁体   中英

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. like this one:

void DoSomeLongRunningTask(out int taskProgress);

I need this inside an async method on an ASP.NET MVC 4 Controller. The taskProgress out parameter will feed a progressbar-like component.

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.

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

DoSomeLongRunningTask returns a Task in this case, since the return type is void , which will be completed in the future when the method finishes.

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.

Here is an example in case you want to implement progress next time, and you do have control over the async method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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