2016-09-20 59 views
0

这是我想要实现的。线程在C中使用WaitHandles等待#

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

现在,从主页我去了一个不同的功能,说类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

你需要提供一个[mcve]给我们回答这个问题。 – Enigmativity

+0

当主页加载并启用“FindProduct”后,只有当Post登录调用返回时,才能将Post登录操作作为“Async-Await”调用进行。提供关于你的系统的更多细节,我假设它的ASP.Net MVC能够进行'Async'调用,在这种情况下使用'WaitHandles'会导致死锁。 –

+0

@MrinalKamboj问题是我使用C#2.0。有很多传统系统需要2.0,所以我没有选择升级。我怀疑它是否有异步。 问题在于我是线程概念的新手。 :| – alfah

回答

1

这里是一般的想法如何使用EventWaitHandle s。在完成这项工作之前,你需要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 
     } 
    } 
} 
0

如果你不希望你的逻辑与坐等或引发一个事件最简单的解决复杂化将是只需设置一个会话变量为true完成PerformLoginAsyncThread函数内部,并在您检查OnClickFindProduct为会话变量。