7
Answers

How to notify main thread from worker thread?

Hi, I’m new to C# and I’m having a problem trying to notify the main thread from a worker thread.

My app has to periodically check (say every 10 secs) if it is connected to a server. To do this I’ve used a timer. As I understand, every 10 secs the timer executes the method CheckConnection (and this is done with a pooled thread). In CheckConnection I want to check if I’m connected to a particular server, if I’m not (i.e. server has gone down) I want to somehow notify the main thread and get the main thread to execute the DealWithServerDown method. I’ve seen lots of examples of this kind of problem, but it’s always using Forms. My solution needs to work for both console and GUI apps.

Any help would be REALLY appreciated. Thanks for looking! 

using System;

using System.Threading;

class Program

{

    static void Main()

    {

      Timer tmr = new Timer (CheckConnection, "Checking...", 10000,10000);

      Console.ReadLine();

      tmr.Dispose();         // End the timer

  }

 

  static void CheckConnection (object data)

  {

     // This runs on a pooled thread

     Console.WriteLine (data);         

 

     // Check if connected to network here

 

     if( notConnected)

     {

       // Notify main thread that it needs to call the DealWithServerDown method

       // Set timer interval to not check again

     }

  }

 

   public void DealWithServerDown()

   {

     // Main thread to execute this

   }

}

 

 

 

Answers (7)