如何知道任务是否同步完成?

问题描述:

我微弱地记得有一个属性,该属性告诉我们任务是否同步执行,但是我的记忆刚刚使我失败。还是可能没有,我将 IAsyncResult.CompletedSynchronously 与此混在一起?

I faintly remember there being a property that tells us whether a task executed synchronously but my memory fails me just now. Or may be there isn't and I am mixing up the IAsyncResult.CompletedSynchronously with this one?

检查此内容:任务.IAsyncResult.CompletedSynchronously属性

其描述看起来很像答案:

It's description looks much like the answer:


获取操作是否同步完成的指示。

Gets an indication of whether the operation completed synchronously.

要检查属性值,您必须强制转换 Task 放入 IAsyncResult ,因为 Task 明确实现了它。

In order to check the property value you will have to cast the Task into IAsyncResult because the Task implements it explicitly.

bool? result = (myTask as IAsyncResult)?.CompletedSynchronously;

可以使用扩展方法代替显式强制转换:系统$ c中定义的WindowsRuntimeSystemExtensions.AsAsyncOperation $ c>名称空间:

Instead of the explicit cast you can use the extension method: WindowsRuntimeSystemExtensions.AsAsyncOperation defined in the System namespace:

bool result = myTask.AsAsyncOperation().CompletedSynchronously;

尽管当前属性实现。从2016年10月1日开始,它始终返回 false 。这可能会发生变化。

As reasonably pointed out in the comment though there is a gag in the current property implementation. As of the first of October 2016 it always returns false. This is a subject to change.