开发者

When running the following code from a unit test I find that the task is calling back to a different thread that the synchonizationContext

When running the following code from a unit test I find that the task is calling back to a different thread than the parent's. I didn't have any trouble with this in a console or WPF but it when it comes to a unit test where the parent is not the main/UI thread there seems to be some different behavior. How could I make this callback to the exact same thread as the parent?

On this machine I am getting the following output for this code:

the parent thread is: 7

the child thread is: 8

the output thread is: 9

0

the output thread is: 10

1

the output thread is: 9

2

...

[TestFixture]
public class TplTesting {
private SynchronizationContext synchronizationContext;

[Test]
public void TaskRunsAndReportsBackToTheUiOnItsOwn() {
Debug.WriteLine("the parent thread is: " + Thread.CurrentThread.ManagedThreadId);
Action<string> callbac开发者_开发问答k = UpdateIndex;
SendOrPostCallback postCallback = obj => callback((string)obj);

SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
synchronizationContext = SynchronizationContext.Current;

Task task = Task.Factory.StartNew(() => {
Debug.WriteLine("the child thread is: " + Thread.CurrentThread.ManagedThreadId);    
for (int i = 0; i < 100; i++) {                        synchronizationContext.Post(postCallback,i.ToString());
   Thread.Sleep(100);
  }
 });

 Task.WaitAll(new[] {task});
}

void UpdateIndex(string output) {
   Debug.WriteLine("the output thread is: " + Thread.CurrentThread.ManagedThreadId);    
   Debug.WriteLine( output);    
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜