7

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);
    }
}
tig
  • 3,424
  • 3
  • 32
  • 65
  • You can always disable the warning in this place by wrapping the code block in `#pragma warning disable/enable` (I don't remember the warning code now though, sorry)... – Patryk Ćwiek Sep 02 '13 at 16:02
  • 1
    Take a look here http://msdn.microsoft.com/en-us/library/vstudio/hh873131.aspx It is suggested that you suppress the warning in such cases. – Nikola Dimitroff Sep 02 '13 at 16:05
  • Closely related question: http://stackoverflow.com/questions/22864367/fire-and-forget-approach – Søren Boisen Jun 03 '15 at 09:22

3 Answers3

17

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());
dtb
  • 213,145
  • 36
  • 401
  • 431
2

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

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.

Community
  • 1
  • 1
Søren Boisen
  • 1,669
  • 22
  • 41