Jedi31
Jedi31

Reputation: 745

Difference in task processing

Let's suppose that I Have two methods, like this...

public void MyMethod()
{
    // do some stuff
}

public Task MyMethodAsync()
{
    //run MyMethod asynchronously
}

What is the best form to execute it in async way?

Like this

public Task MyMethodAsync()
{
    return Task.Run(() => MyMethod());
}

or like this?

public async Task MyMethodAsync()
{
    await Task.Run(() => MyMethod());
}

Upvotes: 1

Views: 85

Answers (3)

Robert McKee
Robert McKee

Reputation: 21487

It's better to go the other way around. Build the inner task as async, and then let all the callers who can't use the async method use the async one internally and wait on it.

public void MyMethod()
{
    MyMethodAsync().Wait();
}

public async Task MyMethodAsync()
{
    // do some stuff
}

Both of your methods aren't truly making anything async. Async isn't about running something in the background, that's the realm of the Task library (or parallel extensions, or threading, etc). Async is about being able to re-use a single thread for multiple things when it has nothing better to do -- which makes thing more scalable. Making a pseudo-async method is just hiding the fact that you are using a NEW thread instead of reusing the same thread, which makes the system LESS scalable.

In order to do that, true async processes need to be written that way from the inside out. Everything (or at least the parts that are time consuming) need to rely on async methods that do that. For example, making a SOAP call where the thread is going to basically just sit idle while waiting for the call to return, or a database call, or file I/O. Async allows that thread to go do something else useful instead of just sitting idle.

Upvotes: 1

moswald
moswald

Reputation: 11667

You should read Stephen Cleary's tutorial on when -- and when not -- to use Task.Run.

Short answer: don't use Task.Run to create a fake async method. If your code isn't truly async, then let the caller decide if it should use a thread (or whatever) to call your code.

Upvotes: 3

Felix Castor
Felix Castor

Reputation: 1675

In the case of your first method, you may as well just have a task on a separate thread. It's not really async because you aren't clearly waiting for the thread to end to start a new process. If you called this it would continue before the task was complete.

public Task MyMethodAsync()
{
    return Task.Run(() => MyMethod());
}

Looking at the second version. You are waiting for the task to complete so that you can do something after without holding up the current thread.

public async Task MyMethodAsync()
{
    await Task.Run(() => MyMethod());
    DoMoreWork();
    //Do something following the completion of the task 
     //without binding up the calling thread, but actually complete it on that thread.
}

Upvotes: 1

Related Questions