Thread wait using WaitHandles in C#

130 Views Asked by At

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
         }
    }
}
2

There are 2 best solutions below

0
slawekwin On BEST ANSWER

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
        }
    }
}
0
snit80 On

If you don't want to complicate your logic with await or raising an event the simplest solution would be inside the PerformLoginAsyncThread function just set a session variable to true on complete and in your OnClickFindProduct check for the session variable.