Water Cooler v2 Water Cooler v2 - 1 year ago 109
C# Question

How to know if a task completed synchronously?

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

with this one?

Answer Source

Check this: Task.IAsyncResult.CompletedSynchronously Property

It's description looks much like the answer:

Gets an indication of whether the operation completed synchronously.

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;

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

bool result = myTask.AsAsyncOperation().CompletedSynchronously;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download