2014-03-04 5 views
4

아마도 어리석은 질문 일 수 있습니다.어떻게 Task가 IAsyncResult를 구현하지만 AsyncWaitHandle 멤버를 포함하지 않습니까?

Task 클래스는이 방법을 선언 :

public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable 

IAsyncResult 인터페이스는 다음과 같이 선언 :

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

그러나 회원 AsyncWaitHandleTask 클래스 또는 인스턴스에 존재하지 않습니다.

이 코드 :

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

이 컴파일 오류를 발생시킵니다 :

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?)

그러나,이 컴파일뿐만 아니라 :

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

그러나 구성원이 존재하기 때문에 또한, 작동합니다. 이 마법은 무엇인가?

이것은 컴파일러의 트릭입니까 아니면 다른 방식으로 숨겨져 있습니까?

건배. 먼저 캐스팅이 명시 적으로, 그래서

+1

+1 마술. – Gusdor

답변

6

Task 구현 IAsyncResult :

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

명시 구현과 같이 정의는 :

public class Task : IAsyncResult 
{ 
    WaitHandle IAsyncResult.AsyncWaitHandle 
    { 
     get { ... } 
    } 
} 
+0

그래서 명시 적 구현은 공개되지 않기 때문에 메타 데이터를 통해 Visual Studio에서이를 볼 수 없습니다. 나는 그것에 대해 생각하지 않았다. 감사. – vtortola

2

은 MSDN 문서는 매우 잘 정리해.

The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class.

interface IControl 
{ 
    void Paint(); 
} 
interface ISurface 
{ 
    void Paint(); 
} 
class SampleClass : IControl, ISurface 
{ 
    void IControl.Paint() 
    { 
     System.Console.WriteLine("IControl.Paint"); 
    } 
    void ISurface.Paint() 
    { 
     System.Console.WriteLine("ISurface.Paint"); 
    } 
} 

여기 테이크 아웃

http://msdn.microsoft.com/en-us/library/ms173157.aspx에서는 명시 적 인터페이스 구현이 개인 및 컴파일러 마법 바인딩 있다는 것입니다.

+0

끔찍한 일로 보입니다. 이것은 LSP에서 구부러진 것이 아닙니까? – vtortola

+0

@vtortola는 인터페이스에 대한 고려에 따라 곧장 위반합니다. 그러나 인터페이스는 추상 유형이 아닙니다. 그들은 단순히 '유형'인터페이스로 안전 캐스트를 할 수 있다고 말한 계약입니다. 나는 팬이 아니지만 일관성이있다. – Gusdor

+1

@vtortola 나는 SRP 위반에 대해 구체적으로 설명합니다. – Gusdor