Is there a surefire way to not wait for a process?

0

Is there a secure way to not wait for a process in .NET?

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

void GravarLog()
{
    // ...
}

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

An alternative, however very volatile, would be async void as a fire and forget ":

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

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

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

How do not you have to "wait" for a method to finish safely?

    
asked by anonymous 28.07.2017 / 22:32

2 answers

1

I ran in the background creating a new thread .

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

void GravarLog()
{
    // operação síncrona
}
    
01.08.2017 / 00:45
1

One alternative I've always used is to call TaskFactory . I've never heard a bad word about it, but I may be wrong. I've never had a problem with it:

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

So it will be called in the background, without needing to use async .

    
29.07.2017 / 05:16