【问题标题】:Alternative to Task.Run that doesn't throw warning不引发警告的 Task.Run 的替代方案
【发布时间】:2015-06-03 17:21:33
【问题描述】:

以下代码按我的意愿运行,但会导致警告:

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

【问题讨论】:

标签: c# async-await tcpclient


【解决方案1】:

当您既不awaitTask返回的Task.Run Method也不将其存储到await时触发警告。如果您想要即发即弃的行为,您可以简单地存储任务,但永远不要 await 它:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      另请参阅 Stephen Clearys answer 关于即发即弃异步操作的一般问题。当您在 WPF 或 ASP.NET 等非默认同步上下文中运行时,他的 async-void 解决方案非常棒,因为任何异常都会自动回传到同步上下文,因此它们不会被忽视。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        相关资源
        最近更新 更多