Thread wait using WaitHandles in C#

By : alfah
Source: Stackoverflow.com
Question!

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
         }
    }
}
By : alfah


Answers

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.

By : snit80


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
        }
    }
}
By : slawekwin


I don't have the privalage to comment but you can use the required field as follows

 <input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" required=true />

using this way the user will have to click all the required fields before submitting a form.



This video can help you solving your question :)
By: admin