gpt4 book ai didi

.net - 为什么 SynchronizationContext 不能正常工作?

转载 作者:行者123 更新时间:2023-12-04 13:42:36 26 4
gpt4 key购买 nike

我有以下代码:

[TestMethod]
public void StartWorkInFirstThread()
{
if (SynchronizationContext.Current == null)
SynchronizationContext.SetSynchronizationContext(
new SynchronizationContext());

var syncContext = SynchronizationContext.Current;

Console.WriteLine("Start work in the first thread ({0})",
Thread.CurrentThread.ManagedThreadId);

var action = ((Action) DoSomethingInSecondThread);
action.BeginInvoke(CallbackInSecondThread, syncContext);

// Continue its own work
}

private static void DoSomethingInSecondThread()
{
Console.WriteLine("Do something in the second thread ({0})",
Thread.CurrentThread.ManagedThreadId);
}

private void CallbackInSecondThread(IAsyncResult ar)
{
Console.WriteLine("Callback in the second thread ({0})",
Thread.CurrentThread.ManagedThreadId);
var syncContext = (SynchronizationContext) ar.AsyncState;
syncContext.Post(CallbackInFirstThread, null);
}

private void CallbackInFirstThread(object obj)
{
Console.WriteLine("Callback in the first thread ({0})",
Thread.CurrentThread.ManagedThreadId);
}

我希望最后一个方法在第一个线程中执行,即从 SynchronizationContext 获取的初始线程,因为我调用 Post()这个上下文的方法。 IE。像这样:
Start work in the first thread (28)
Do something in the second thread (17)
Callback in the second thread (17)
Callback in the first thread (28)

不就是SynchronizationContext的意思吗?但实际上我有以下输出:
Start work in the first thread (28)
Do something in the second thread (17)
Callback in the second thread (17)
Callback in the first thread (7)

问题是什么? SynchronizationContext 有什么问题还是我有一些误解?

更新:我将此方法称为使用 Resharper 测试运行程序的单元测试。

最佳答案

http://www.codeproject.com/KB/threads/SynchronizationContext.aspx

有你需要的答案。您必须覆盖 SynchronizationContext使其正确处理您的操作。

阅读从:

Notice that DoWork is executed on thread 11, the same thread as Run1. Not much of a SynchronizationContext into the main thread. Why? What's going on? Well... This is the part when you realize that nothing is for free in life. Threads can't just switch contexts between them, they must have an infrastructure built-in into them in order to do so. The UI thread, for example, uses a message pump, and within its SynchronizationContext, it leverages the message pump to sync into the UI thread.

关于.net - 为什么 SynchronizationContext 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com