Grofit
Grofit

Reputation: 18445

Does adding a Task<T> to the return of a method make it run in a thread?

I am struggling to find any solid information online, but lets pretend I have a method like below:

public int DoSomething()
{
    // some sync logic that takes a while
    return someResult
}

So lets assume it is a method that is completely sync and currently will block the thread the caller is on for 100ms. So then lets say I wanted to create a version that would not block that thread while it executes, is it as simple as just doing:

public Task<int> DoSomethingAsync()
{
    // some sync logic that takes a while
    return Task.FromResult(someResult)
}

As I know Task.Run will cause code to be executed within a thread, but does .net basically interpret any method with a Task/<T> return type to be something that should be non blocking?

(I am hesitant to use the word async as it has mixed meanings in .net, but as shown above there is no await use here)

Upvotes: 0

Views: 100

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

No. All that changing the return type does is... change the return type.

You're changing your promise from "when I return I will give you an int" to "when I return, I will give you something that will eventually provide an int" (with the caveat that the value may, in fact, already be available).

How your method comes up with the Task is entirely an internal implementation detail that is a concern for your method. In your current changed implementation, it does it by running entirely on the same thread from which it was called and then just stuffing the result into a Task at the end - to no real benefit.

If you had added the async keyword and left the return someResult; line you'd have been given more clues about this by the compiler:

This async method lacks 'await' operators and will run synchronously. Consider using ...

Upvotes: 3

Related Questions