3

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();
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
Ree
  • 81
  • 1
  • 7

1 Answers1

6

You can do it like this:

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();

This starts the thRegion1 thread and performs the other part of the work in the current thread. After that work is finished, it calls Join on thRegion1 which will return immediately, if thRegion1 is already finished with its work.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Thanks. But where is thRegion2? Should I remove it from this line from the second process? Thread thRegion2 = new Thread(() => ? – Ree Aug 19 '11 at 14:28
  • @Ree Yes, it was removed, and the work it was doing was moved to the *current thread.* Why have it stay idle when it could be doing useful work? – dlev Aug 19 '11 at 14:29
  • `thRegion2` isn't needed and because of this, it doesn't exist in my code anymore. The work it does has been moved to the current thread as you requested. – Daniel Hilgarth Aug 19 '11 at 14:29
  • So will this make the 2 reagions process in concurrent channels? – Ree Aug 19 '11 at 14:30
  • 1
    @Ree Yes, the first one started in a new thread, and the second one is running at your current thread, so they are both running concurrently. – Jalal Said Aug 19 '11 at 14:34