Run fast things synchronously and time-consuming things asynchronously?

Asked

Viewed 72 times

2

Usually, on . NET, I run things time-consuming asynchronously so as not to stop the thread visual. In a simple example, if I have a loading in the UI, should lengthy things be executed without awaited, they lock that loading, who was executed in the thread visual.

Actions that may be time-consuming, such as processing a list, loops or read files, I run asynchronously. But when I have things I know are not time-consuming, like a simple conditional structure:

public bool? ToBoolean(int input)
{
    if (input == 1)
    {
        return true;
    }
    else if (input == 0)
    {
        return false;
    }

    return null;
}

For these cases, which I know are fast (in theory), I should have something like?

public async Task<bool?> ToBooleanAsync(int input)
{
  return await Task.Run(() => ToBoolean(input));
}

I must perform things quickly asynchronously, and why (or why not)?

1 answer

4


No, there’s no way you’re doing this. In this specific case arming and controlling all asynchronicity infrastructure will take absurdly longer than the execution of this method.

The recommendation for the asynchronous call to compensate is to take 50 milliseconds (on the user’s machine, not on its powerful developer). Even because less time than this is not very perceived by the human, and doing something asynchronous serves only to improve the user experience. It does not perform better or faster. On the contrary, it is even slower.

If that runs on server, on batch, outside user interaction asynchronicity does not help in the same way. It depends on whether the solution developed has a single execution queue or there may be independent executions, who knows until asynchronicity is used to allow more than one execution line, not a clear rule, has to measure. Certainly something so simple does not make up for it. Often it will only make up for much higher times.

  • How do I mount such a structure? Can I create another question

  • 1

    You don’t assemble, this is internal, the compiler generates a part, the libraries do another.

Browser other questions tagged

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