[英]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.