首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用WaitHandles在C#中等待线程

使用WaitHandles在C#中等待线程
EN

Stack Overflow用户
提问于 2016-09-20 05:25:23
回答 2查看 86关注 0票数 0

这就是我想要达到的目标。

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

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

我必须在PerformLoginAsyncThread和OnClickFindProduct上放置等待句柄吗?

代码语言:javascript
复制
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
         }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-20 06:46:42

以下是如何使用EventWaitHandle的一般想法,您需要在完成工作之前对其进行Reset,并在完成工作时使用Set

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

代码语言:javascript
复制
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
        }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2016-09-20 06:56:30

如果您不想让您的逻辑复杂化,等待或引发事件,最简单的解决方案将是在PerformLoginAsyncThread函数中,只需将一个会话变量设置为true,on complete,并在OnClickFindProduct中检查会话变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39586276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档