简体   繁体   English

使用 Dispatcher.RunAsync() 启动任务并立即返回的正确方法是什么?

[英]What is the proper way to use Dispatcher.RunAsync() to start a task and return immediately?

Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    //do something
});

The above code causes Compiler Warning (level 1) CS4014 :上面的代码导致编译器警告(级别 1)CS4014

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.考虑将 await 运算符应用于调用结果。

The behavior is exactly what I want: start the task and let it run in a separate thread and return immediately.行为正是我想要的:启动任务并让它在单独的线程中运行并立即返回。

I can make the warning go away by changing the code to the following:我可以通过将代码更改为以下内容来消除警告:

var v = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    //do something
}); 

I think "var v" is redundant.我认为“var v”是多余的。 Why is the compiler happy with this redundancy?为什么编译器对这种冗余感到满意?

Could anyone shed some light on this?任何人都可以对此有所了解吗?

Why is the compiler happy with this redundancy?为什么编译器对这种冗余感到满意?

Because it uses a very simple heuristic.因为它使用了一个非常简单的启发式方法。 It doesn't do an in-depth analysis of the entire program to determine if every code path (or any code path) observes the results of the Task .它不会对整个程序进行深入分析,以确定是否每个代码路径(或任何代码路径)都观察到Task的结果。 The warning is only triggered by the return value of the Task-returning method (in an async method) not ever being stored or accessed.该警告由从未存储或访问的任务返回方法(在async方法中)的返回值触发。 The main idea here is to prevent someone from calling a method that they don't even realize is asynchronous and unintentionally ignoring the result.这里的主要思想是防止有人调用一个他们甚至没有意识到是异步的方法并且无意中忽略了结果。 Intentionally ignoring the result isn't something it's trying to prevent.故意忽略结果并不是它试图阻止的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Dispatcher.RunAsync()中使用“ await”会引发异常 - Using “await” in Dispatcher.RunAsync() throws an exception 编译器问题,努力使用 Dispatcher.RunAsync() 调用 UI 线程并返回一个值 - Compiler issues, struggling to call UI thread using Dispatcher.RunAsync() and return a value 可移植类库,相当于Dispatcher.Invoke或Dispatcher.RunAsync - Portable class library equivalent of Dispatcher.Invoke or Dispatcher.RunAsync Dispatcher.RunAsync(应用程序调用了已编组为不同线程的接口。) - Dispatcher.RunAsync (The application called an interface that was marshalled for a different thread.) 将Dispatcher.RunAsync()中的值返回到后台线程 - Returning a value from Dispatcher.RunAsync() to background thread 使用异步回调了解 Dispatcher.RunAsync 并等待 UI 相关任务 - Understanding Dispatcher.RunAsync with an async callback and awaiting UI related tasks JoinableTaskFactory.RunAsync 的正确用法是什么? - What is the proper usage of JoinableTaskFactory.RunAsync? 在.net 4.0中启动任务的正确方法 - Proper way to start Task in .net 4.0 检测父任务取消的正确方法是什么? - What is the proper way to detect parent Task cancellation? 正确的方法来实现返回Task的方法<T> - Proper way to implement methods that return Task<T>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM