Search code examples
c#multithreadingwaithandle

Thread wait using WaitHandles in C#


Here is what I'm trying to achieve.

I have a login class. Once the user is authenticated, some post login operations are done in a thread. And the user gets to home page.

Now from home page I go to a different functionality, say class FindProduct. I need to check if post login operations in the login thread are completed. Only if post login operation is completed I allow to enter the functionality.

Do I have to put wait handles on PerformLoginAsyncThread as well as OnClickFindProduct?

Class Login
{
   public bool Login(Userinfo)
   {
      // do tasks like authenticate
      if(authenticationValid)
         {
          PerformLoginAsyncThread(UserInfo)
          //continue to homepage
         }
   }   

}

Class HomePage
{
   public void OnClickFindProduct
   {
     if(finishedPostLoginThread)
        // proceed to Find Product page
     else
         {
           //If taking more than 8 seconds, throw message and exit app
         }
    }
}

Solution

  • Here is the general idea how to use EventWaitHandles. You need to Reset it before doing the work, and Set it when you are done.

    In the example below I have made the ResetEvent property static, but I suggest you pass the instance somehow instead, I just could not do it without more details about your architecture.

    class Login
    {
         private Thread performThread;
         public static ManualResetEvent ResetEvent { get; set; }
         public bool Login(Userinfo)
         {
            // do tasks like authenticate
            if(authenticationValid)
            {
                PerformLoginAsyncThread(UserInfo);
                //continue to homepage
            }
        }   
    
        private void PerformLoginAsyncThread(UserInfo)
        {
            ResetEvent.Reset();
            performThread = new Thread(() => 
            {
                //do stuff
                ResetEvent.Set();
            });
            performThread.Start();
        }
    }
    
    class HomePage
    {
        public void OnClickFindProduct
        {
            bool finishedPostLoginThread = Login.ResetEvent.WaitOne(8000);
            if(finishedPostLoginThread)
            {
                // proceed to Find Product page
            }
            else
            {
                //If taking more than 8 seconds, throw message and exit app
            }
        }
    }