我如何在调用SomeAsyncMethod的同一线程上调用onCompleteCallBack方法?
public void SomeAsycMethod ( Action<object> onCompleteCallBack ) { // get the current thread /* var ThisThread = Thread.CurrentThread. */ Task.Factory.StartNew( () => { Thread.Sleep( 1000 );// do some work; // lastly call the onCompleteCallBack on 'ThisThread' onCompleteCallBack( "some result" ); // I am looking for something like: /* ThisThread.Invoke("some result"); */ }); }
解决方法
虽然你不能保证你会在同一个线程上调用回调,但你可以保证它将在同一个
Synchronization Context中被调用(假设原始调用中存在一个).
public void SomeAsycMethod ( Action<object> onCompleteCallBack ) { // get the current context var context = SynchronizationContext.Current; Task.Factory.StartNew( () => { Thread.Sleep( 1000 );// do some work; // lastly call the onCompleteCallBack on 'ThisThread' onCompleteCallBack( "some result" ); // I am looking for something like: context.Post(s => onCompleteCallBack ("some result"),null); }); }
例如,在Windows窗体或WPF程序中,上面将确保在GUI线程上调用回调(相应地通过消息循环或调度程序).类似于ASP.NET上下文.
话虽如此,我同意Justin Harvey的回复任务< T>可能会是一个更好的设计.