Is there a difference between Task.Fromresult and Task.Factory.Startnew?

Asked

Viewed 44 times

2

Given a method in precise return a Task<T>.

Example:

public Task<MyResult> Handle();

I can make the following implementations:

Thus:

public Task<MyResult> Handle()
{
    for (int i = 0; i < 1000; i++)
    {
        // alguma coisa
    }

    return Task.FromResult(new MyResult());
}

and so:

public Task<MyResult> Handle()
{
    return Task.Factory.StartNew(() =>
    {
        for (int i = 0; i < 1000; i++)
        {
            // alguma coisa
        }

        return new MyResult();
    });
}
  • There is some difference between these implementations?
  • Which would be the most recommended?
  • In the first example, there may be loss of performance?

1 answer

1


There is some difference between these implementations?

The first only creates a result of a task, it does not perform a task. If you need to perform a task it should not be used. His function is to encapsulate an object in a task, not to execute it. It does not mean that it does not execute the method, only that it will not be done as a task.

The second performs a task and delivers a result. I understand that it is only creating a Task to meet the demand of the method that is implementing that requires that signature, so there’s no point in using it.

Which would be the most recommended?

The first, if you can use it. If you need to do the second consider using Task.Run(). Can read more about.

In the first example, there may be loss of performance?

The opposite, usually. It doesn’t mean it’s the best ever, being faster to execute is different from delivering the result in the best way. But do not think that there will be great difference, it is something minimal. As it is not running asynchronously I did not see advantage in the second, it is only complication.

If MyResult() for too long it may be interesting, in some scenarios, to make the execution be asynchronous so as not to block the execution, but it will not make anything run faster. If it takes little time the asynchronicity can be harmful even running in parallel.

  • I’ll read this file, I’ve never read anything about it... Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.