如何在线程中同步2个进程以便它们一起运行?

时间:2011-08-19 14:23:49

标签: c# multithreading .net-3.5 synchronization

我目前有这段代码(感谢您的帮助)。我需要创建第一个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();

1 个答案:

答案 0 :(得分:6)

你可以这样做:

Thread thRegion1 = new Thread(() =>
        {
            if (shawRegion1.Trim().Length > 0)
            {
                returnMessage = ProcessMessage(string.Format(queueName, 
                                                             shawRegion1));
                Logger.Log(returnMessage);
            }
        });

thRegion1.Start();

if (shawRegion2.Trim().Length > 0)
{
    returnMessage = ProcessMessage(string.Format(queueName, shawRegion2));
    Logger.Log(returnMessage);
}

thRegion1.Join();

这将启动thRegion1线程,并在当前线程中执行其他工作。该工作完成后,如果Join已完成其工作,则会在thRegion1上调用thRegion1,该{{1}}会立即返回。