D
D
Dmitry Gavrilenko2019-01-23 17:08:00
.NET
Dmitry Gavrilenko, 2019-01-23 17:08:00

Does the absence of await guarantee the execution of an async method?

Good afternoon.
Suppose there is a code

public async Task<int> Process()
{
    // logic
    var i = await _context.SaveChangesAsync();

    await _notification.Notify(); // <---- возвращает таск.

    return i;
}

As already written, _notification.Notify() returns a task that we can AWAIT. But let's say this method runs for an hour, and I don't have to wait for it to return i
Question: can I remove await and not wait for Notify() to complete, but still be sure that it will complete 100% (ignoring for possible exceptions that occur within it)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shai_hulud, 2019-01-23
@Maddox

await only subscribes to the result of the awaitable (in our case, Task). And whether this will be executed does not depend on await i.e. from those who can wait. those. the answer is yes, Notify() will thresh itself for hours. If there is an error inside, it is better to subscribe to the result and skip the error. Notify().ContinueWith(t=> { var x = t.Exception; ... }); You shouldn't do this, it's a mistake that is often made. 'async => ()' is already a state machine that is started by a call, it does not need to be scheduled through tasks. Correct example:

new Func<Task>(async =>  {
    try
    {
        await _notification.Notify();
    } catch(Exception ex) {
        // TODO: Логируем исключение
    }
}).Invoke();

But again, all this is not needed in the current task, you can call ContinueWith.

A
Alexander Yudakov, 2019-01-23
@AlexanderYudakov

This is how it's done:

Task.Run(async () =>
{
    try
    {
        await _notification.Notify();
    } catch(Exception ex) {
        // TODO: Логируем исключение
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question