2016-09-20 72 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爲會話變量。