Task.Run alternative that does not throw a warning

The following code works the way I want, but it triggers 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 start this thread in a beautiful 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); } } 
+4
source share
3 answers

A warning is triggered if you do not await Task returned by the Task.Run Method and save it until await I later. If you want to forget behavior differently, you can just save the task, but never await it:

 Task task = Task.Run(() => ReadSubscriptionResponses()); 
+11
source

If you really want to disgrace and forget behavior, you can call ThreadPool.QueueUserWorkItem() .

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

+2
source

Also see Stephen Clearys answer to a general question about asynchronous fire-and-forget operations. Its async-void solution works fine when you work in a different synchronization context, such as WPF or ASP.NET, because any exceptions will be automatically sent back to the synchronization context, so they will not remain invisible.

+1
source

Source: https://habr.com/ru/post/1500178/


All Articles