簡體   English   中英

不會拋出警告的Task.Run的替代方案

[英]Alternative to Task.Run that doesn't throw 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.

是否有一個替代Task.Run()將以一個簡潔的方式開始這個線程?

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

當您既沒有await Task.Run方法返回的任務也沒有將它存儲到稍后await我時觸發警告。 如果你想要發射冒險行為,你可以簡單地存儲任務,但永遠不會await它:

Task task = Task.Run(() => ReadSubscriptionResponses());

如果您真的想要發射冒險行為,可以調用ThreadPool.QueueUserWorkItem()

但是,請確保您知道如何處理該函數的錯誤。

另請參閱Stephen Clearys對“即發即棄”異步操作的一般問題的回答 當您在非默認同步上下文(如WPF或ASP.NET)中運行時,他的async-void解決方案非常棒,因為任何異常都會自動發布回同步上下文,因此它們不會被忽略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM