Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to Task.Run that doesn't throw warning

The following code works as I want it to, but causes a warning:

Warning 1 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Is there an alternative to Task.Run() that will kick off this thread in a nice terse way?

/// <summary>
/// StartSubscriptionsAsync must be called if you want subscription change notifications.
/// This starts the subscription engine. We always create one subscription for
/// Home DisplayName to start (but ignore any updates).
/// </summary>
public async Task StartSubscriptionsAsync(){
    await _subscriptionClient.ConnectAsync(Host, Port);

    // Generates a compiler warning, but it is what we want
    Task.Run(() => ReadSubscriptionResponses());

    // We do a GetValue so we know we have a good connection
    SendRequest("sys://Home?f??" + "Name");

    if (FastMode) EnableFastMode();

    foreach (var subscription in _subscriptions) {
        SendSubscriptionRequest(subscription.Value);
    }
}
like image 597
tig Avatar asked Sep 02 '13 15:09

tig


People also ask

Is it good to use Task run?

You can use Task. Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available. The async-based approach to asynchronous programming is preferable to existing approaches in almost every case.

Can we use Task without async?

If you use await in your code, you are required to use the async keyword on the method. If you use async and want to return an actual type, you can declare that your method returns the type as a generic Task like this Task<int> . Task<TResult> , for an async method that returns a value.

What happens if you dont await Task?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.

Is Task run asynchronous?

In . NET, Task. Run is used to asynchronously execute CPU-bound code.

Does Task run use a new thread?

NET code does not mean there are separate new threads involved. Generally when using Task. Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR.


1 Answers

The warning is triggered when you neither await the Task returned by the Task.Run Method nor store it to await i later. If you want fire-and-forget behavior, you can simply store the task but never await it:

Task task = Task.Run(() => ReadSubscriptionResponses());
like image 111
dtb Avatar answered Oct 07 '22 20:10

dtb