簡體   English   中英

如何在線程中同步2個進程以便它們一起運行?

[英]How do I synchronize 2 processes in threads so they run together?

我目前有這個代碼(感謝此處的幫助)。 我需要創建第一個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();

你可以這樣做:

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線程並執行當前線程中的其他工作。 這項工作完成后,它會調用JointhRegion1將立即返回,如果thRegion1已與它的工作完成了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM