以下代码按我的意愿运行,但会发出警告:
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);
}
}
答案 0 :(得分:12)
如果Task await
await
{}返回await
并且Task task = Task.Run(() => ReadSubscriptionResponses());
我迟迟未将其存储到{{1}},则会触发警告。如果你想要发射冒险行为,你可以简单地存储任务,但绝不能{{1}}它:
{{1}}
答案 1 :(得分:2)
如果您真的想要发射性行为,可以致电ThreadPool.QueueUserWorkItem()
。
但是,请确保您知道如何处理该功能的错误。
答案 2 :(得分:1)
另见Stephen Clearys answer关于即发即弃异步操作的一般问题。当您在非默认同步上下文(如WPF或ASP.NET)中运行时,他的async-void解决方案非常棒,因为任何异常都会自动发布回同步上下文,因此它们不会被观察到。< / p>