如何同步线程中的 2 个进程以便它们一起运行?
我目前有这段代码(感谢这里的帮助)。我需要将第一个 ProcessMessage 创建为线程,并同步运行第二个 ProcessMessage(在当前线程上),然后在单个线程上执行 Join。否则,我将让三个线程有效地完成两件事。我该如何修改它来实现它?我使用的是.NET 3.5
Thread thRegion1 = new Thread(() =>
{
if (Region1.Trim().Length > 0)
{
returnMessage = ProcessTheMessage(string.Format(queueName, Region1));
Logger.Log(returnMessage);
}
});
Thread thRegion2 = new Thread(() =>
{
if (Region2.Trim().Length > 0)
{
returnMessage = ProcessTheMessage(string.Format(queueName, Region2));
Logger.Log(returnMessage);
}
});
thRegion1.Start();
thRegion2.Start();
thRegion1.Join();
thRegion2.Join();
I currently have this code (thanks for the help from here). I need to create the first ProcessMessage as a thread and run the second ProcessMessage
synchronously (on the current thread), then perform the Join on the single thread. Otherwise, I'll have three threads doing effectively two things. How do I modify this to accomplish it? I am on .NET 3.5
Thread thRegion1 = new Thread(() =>
{
if (Region1.Trim().Length > 0)
{
returnMessage = ProcessTheMessage(string.Format(queueName, Region1));
Logger.Log(returnMessage);
}
});
Thread thRegion2 = new Thread(() =>
{
if (Region2.Trim().Length > 0)
{
returnMessage = ProcessTheMessage(string.Format(queueName, Region2));
Logger.Log(returnMessage);
}
});
thRegion1.Start();
thRegion2.Start();
thRegion1.Join();
thRegion2.Join();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样做:
这将启动 thRegion1 线程并在当前线程中执行其他部分的工作。该工作完成后,它会对
thRegion1
调用Join
,如果thRegion1
已完成其工作,该操作将立即返回。You can do it like this:
This starts the
thRegion1
thread and performs the other part of the work in the current thread. After that work is finished, it callsJoin
onthRegion1
which will return immediately, ifthRegion1
is already finished with its work.