PeterLiguda
PeterLiguda

Reputation: 792

Run any C# method async. Possible?

With Task.Run() you can run any method async, like

public int Increase(int val)
{
   return val + 1
}


int increased = await Task.Run ( () => return Increase(3) );

Is it possible to create an extension method, to just run any method as async like

var val = 1;
int increased = await Increased(3).AsAsync();

Upvotes: 1

Views: 171

Answers (2)

user6996876
user6996876

Reputation:

If you have a CPU bound task and you want to use async as a convenient wrapper also for CPU bound operations, you can define an extension (vaguely based on this GetTask example)

public static class AsyncExtensions
{
    public static Task<U> AsCpuBoundAsync<T,U>(this Func<T,U> func, T t) 
    {
        return Task.Run(() => func(t));  
    }
}

to wrap a function

    public static int Increase(int val)
    {
       //doing CPU bound activities...
       return val + 1;
    }

as follows

   int increased = await ((Func<int,int>)(t =>
       Increase(t))).AsCpuBoundAsync(3);

Upvotes: 1

Servy
Servy

Reputation: 203844

There is no way you could write an AsAsync method that would do what you're suggesting. In the code Increased(3).AsAsync() You have already synchronously executed Increased(3) and computed its result before AsAsync is called. It's too late to not execute that code before continuing.

Upvotes: 2

Related Questions