简体   繁体   中英

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);
    }
}

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());

If you truly want fire-and-forget behavior, you can call ThreadPool.QueueUserWorkItem() .

However, make sure you know how you will handle errors from that function.

Also see Stephen Clearys answer to the general question of fire-and-forget async operations. His async-void solution is great when you are running in a non-default synchronization context such as WPF or ASP.NET, because any exceptions will automatically be posted back to the synchronization context, so they won't go unobserved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM