0

这是我想要实现的目标。

我有一个登录类。一旦用户通过身份验证,一些登录后操作将在一个线程中完成。用户进入主页。

现在从主页我转到一个不同的功能,比如类 FindProduct。我需要检查登录线程中的登录后操作是否完成。只有在登录后操作完成后,我才允许进入该功能。

我是否必须在 PerformLoginAsyncThread 和 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
         }
    }
}
4

2 回答 2

1

以下是如何使用EventWaitHandles 的总体思路。Reset在做工作之前你需要它,Set当你完成时它。

在下面的示例中,我将ResetEvent属性设为静态,但我建议您以某种方式传递实例,如果没有有关您的体系结构的更多详细信息,我将无法做到这一点。

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
        }
    }
}
于 2016-09-20T06:46:42.033 回答
0

如果您不想通过等待或引发事件使逻辑复杂化,最简单的解决方案是在 PerformLoginAsyncThread 函数中,只需在完成时将会话变量设置true 并在 OnClickFindProduct 中检查会话变量。

于 2016-09-20T06:56:30.433 回答