10

를 사용하여 클래식 비동기 패턴을 구현,하지만 내 실행 속도가 느려질 수 있습니다.내가 트랙의 방법을 쓸 수 WF (4)에 대한 사용자 정의 TrackingParticipant을 구현하기 위해 노력하고있어 TPL

어떻게이/EndTrack가 .NET 4.0의를 사용하여 재정의 시작 구현할 수 있습니다 태스크 라이브러리 (TPL)를 병렬? 나는 TPL and Traditional .NET Asynchronous Programming을 보았지만 여기에 적용하는 방법을 모르겠습니다. TrackingParticipant는 .NET의 일부인 가상 메소드를 사용하여 미리 정의 된 클래식 비동기 패턴이

참고.

public class MyTrackingParticipant : TrackingParticipant 
{ 
    protected override IAsyncResult BeginTrack(
     TrackingRecord record, TimeSpan timeout, 
     AsyncCallback callback, object state) 
    { 
     // ? 
    } 

    protected override void EndTrack(IAsyncResult result) 
    { 
     // ? 
    } 

    protected override void Track(TrackingRecord record, TimeSpan timeout) 
    { 
     // synchronous code to be called 
    } 
} 

답변

18

이 고전 APM 프로그래밍 모델 구현하는 함께 일반적인 패턴 다음 EndXXX 방법은 당신이 실제로 TaskResult 속성을 반환 결과를 반환하는 대신 단지 호출하는 경우

protected override IAsyncResult BeginTrack(TrackingRecord record, TimeSpan timeout, AsyncCallback callback, object state) 
{ 
    Task result = Task.Factory.StartNew(
     (taskState) => 
     { 
      // ... your async work here ... 
     }, 
     state); 

    if(callback != null) 
    { 
     result.ContinueWith((t) => callback(t)); 
    } 

    return result; 
} 

protected override void EndTrack(IAsyncResult asyncResult) 
{ 
    // Call wait to block until task is complete and/or cause any exceptions that occurred to propagate to the caller 
    ((Task)asyncResult).Wait(); 
} 

Wait. 예를 들어 :

protected override int EndAwesomeCalculation(IAsyncResult asyncResult) 
{ 
    // This will block until the result is available and/or cause any exceptions that occurred propagate to the caller 
    return ((Task<int>)asyncResult).Result; 
} 
+0

감사합니다! 이 작품; 이상하게도 작업 흐름은 Track()이 완료 될 때까지 계속 차단됩니다. (그것은이/종료 방법을 시작 전화 않습니다.) 내가 원하는 동작을 얻을 수있는 큐를 구현해야 할 것처럼 보인다. (정답에서 벗어나지 마십시오!) – TrueWill