Task.Run 的替代方法,不引发警告



以下代码按照我的意愿工作,但会引起警告:

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任务返回的任务时,就会触发警告。请运行方法,也不要稍后将其存储到await i中。如果你想要即发即弃行为,你可以简单地存储任务,但决不能await it:

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

如果您真的想要即发即弃行为,您可以调用ThreadPool.QueueUserWorkItem()

但是,请确保您知道如何处理该函数中的错误。

另请参见Stephen Clearys对即发即弃异步操作一般问题的回答。当您在非默认同步上下文(如WPF或ASP.NET)中运行时,他的异步void解决方案非常棒,因为任何异常都会自动发布回同步上下文,因此不会被忽视。

最新更新