Is it possible to use the same aync method signature in C # 5.0 and be able to decide later how to execute such a method

I want to use recent asynchronous C # 5.0 methods, but in some specific way.

Consider the following code example:

public abstract class SomeBaseProvider : ISomeProvider
{
   public abstract Task<string> Process(SomeParameters parameters);    
}

public class SomeConcreteProvider1 : SomeBaseProvider 
{

   // in this method I want to minimize any overhead to create / run Task
   // NOTE: I remove here async from method signature, because basically I want to run 
   // method to run in sync!
   public override Task<string> Process(SomeParameters parameters) {

      string result = "string which I don't need any async code to get";

      return Task.Run(() => result);
   }
}

public class SomeConcreteProvider2 : SomeBaseProvider 
{

   // in this method, it OK for me to use async / await 
   public async override Task<string> Process(SomeParameters parameters) {

      var data = await new WebClient().DownloadDataTaskAsync(urlToRequest);

      string result = // ... here we convert data byte[] to string some way

      return result;

   }
}

Now, as I will use asynchronous methods (you can ignore the fact that the consumer is actually an ASP.NET MVC4 app in my case ... it could be anything):

public class SomeAsyncController : AsyncController
{

    public async Task<ActionResult> SomethingAsync(string providerId)
    {
       // we just get here one of providers I define above
       var provider = SomeService.GetProvider(providerId);

       // we try to execute here Process method in async. 
       // However we might want to actually do it in sync instead, if  
       // provider is actually SomeConcreteProvider1 object.
       string result = await provider.Process(new SomeParameters(...));

       return Content(result);
     }
} 

As you can see, I have 2 implementations, each of them will work differently: one I want to run in async and not block the flow (SomeConcreteProvider2), and the other I want to be able to start synchronization and not create any object Task, etc. (which I cannot code in the code above, that is, I am creating a new task here!).

, async <T> ?. - ... , - , (.. ), - /I/O .. , , SomeConcreteProvider1 (html), . SomeConcreteProvider2 -, - - , - Async, ( , ).

, : ( ?), , , , , Task.Run(... ) SomeConcreteProvider1.Process?

1: ( , ), , - (, isAsyncImplementation), , , , ( ) : DI - , : D

+5
2

.

SomeConcreteProvider1 TaskCompletionSource

a Task, concurrency.

, await , Task . " " .

0

All Articles