5

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

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

3 回答 3

14

当您既没有Task.Run 方法返回的awaitTask没有将其存储到i 之后,就会触发警告。如果你想要即发即弃的行为,你可以简单地存储任务,但永远不要:awaitawait

Task task = Task.Run(() => ReadSubscriptionResponses());
于 2013-09-02T16:09:56.743 回答
2

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

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

于 2013-09-02T16:01:23.560 回答
1

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

于 2015-06-03T09:21:33.570 回答