Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come Task implements IAsyncResult, but does not contain the AsyncWaitHandle member?

Maybe it is a silly question.

The Task class is declared this way:

public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable

The IAsyncResult interface is declared like this:

public interface IAsyncResult
{
    object AsyncState { get; }
    WaitHandle AsyncWaitHandle { get; }
    bool CompletedSynchronously { get; }
    bool IsCompleted { get; }
}

But the member AsyncWaitHandle does not exist in the Task class or instances.

This code:

System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() => { }); 
t.AsyncWaitHandle.ToString(); 

Raises this compilation error:

Error 1 'System.Threading.Tasks.Task' does not contain a definition for 'AsyncWaitHandle' and no extension method 'AsyncWaitHandle' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?)

However, this not only compiles:

System.IAsyncResult t = new System.Threading.Tasks.Task(() => { }); 
t.AsyncWaitHandle.ToString(); 

But also works, since the member exists. What is this sorcery?

It is a compiler trick or is it being hidden in another way?

Cheers.

like image 949
vtortola Avatar asked Mar 04 '14 14:03

vtortola


1 Answers

Task implements IAsyncResult explicitly, so you have to cast first:

System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() => { }); 
((IAsyncResult)t).AsyncWaitHandle.ToString()

Explicit implementations are defined like:

public class Task : IAsyncResult
{
    WaitHandle IAsyncResult.AsyncWaitHandle
    {
        get { ... }
    }
}
like image 176
Lee Avatar answered Nov 14 '22 23:11

Lee