Is there a sure way not to wait for a lawsuit?

Asked

Viewed 86 times

1

There is a safe way not to wait for a process on . NET?

async Task DoFoo()
{
    // ...
    GravarLog();
    // ...
}

void GravarLog()
{
    // ...
}

In the above code, my entire process will wait for the method to be completed GravarLog(), which to me is not necessary, and that method could be executed in background, without me having to wait for it to run the rest of my code. (log recording was just an example I used to contextualize)

An alternative, however highly volatile, would be async void as a "fire and Forget" (or "fire and crash"):

async Task DoFoo()
{
    // ...
    GravarLog();
    // ...
}

async void GravarLog()
{
    // ...
}

There are many articles and opinions saying to avoid at all costs using async void, because the exception control is different from the . NET standard:

How not to "wait" for a method to be completed safely?

  • 1

    I see no problem in waiting to record a log, because (until today what I saw) recording logs is something very fast. But if it is a cumbersome process, have you considered delegating this responsibility to a Task Scheduler?

  • I’ve never done the treatment of these cases manually (I didn’t have to), I’ve always used tools for this, so I can’t explain how to do the manual process of controlling this. But one tool that takes very good care of it is Hangfire.

  • @Gabrielkatakura was the way I found to contextualize: logs, telemetry =P. I’ll take a look at this Hangfire.

2 answers

1

An alternative I’ve always used is to call TaskFactory. I’ve never heard you say the same wrong thing, but I could be wrong. I’ve never had a problem with the same:

using System.Threading.Tasks;
...
TaskFactory runner = new TaskFactory();
Action task = () => GravarLog();
runner.StartNew(task);

So she will be called in the background, without having to use the async.

  • 1

    would be runner.StartNew(task); ?

  • 1

    My mistake. I forgot to replace this, I just corrected.

1


I circled in the background creating a new thread.

async Task DoFoo()
{
    // ...
    new Thread(() =>
    {
        GravarLog();
    }).Start();
    // ...
}

void GravarLog()
{
    // operação síncrona
}

Browser other questions tagged

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