2012-03-12 28 views
0

我有通過wsdl生成的函數,其中一個函數是異步函數,它也有一個事件。將計時器設置爲異步請求

ws.GetRequest("Login","Username","Password"); 
ws.GetRequestCompleted+=delegate(object sender,WS.GetRequestCompletedEventArgs e) 
{ 
    //somecode 
} 

我想用於請求創建定時器以上,如果一段時間後不會發生GetRequestCompleted,我將顯示一個錯誤消息。 我無權訪問wsdl函數。

回答

2

你需要做兩件事情:

    當請求開始
  • 定時器觸發時,如果回調沒有被稱爲
  • 啓動一個定時器,拋出一個異常

它看起來像是發生在一種方法中,並且您使用匿名方法以及委託簽名,所以我建議使用閉包,如下所示:

// Let's say you want to wait for 5 seconds. 
System.Timers.Timer t = new System.Timers.Timer(5000); 

// Has the timer completed? The callback on the web service? 
bool wsCompleted = false, timerCompleted = false, exceptionThrown = false; 

// Need to synchronize access to above, since it will come back on 
// different threads. 
object l = new object(); 

// Set up the callback on the timer. 
t.Elapsed = delegate(object sender, ElapsedEventArgs e) { 
    // Lock access. 
    lock (l) 
    { 
     // Set the flag to true. 
     timerCompleted = true; 

     // If the web service has not completed and 
     // the exception was not thrown, then 
     // throw your exception here. 
     if (!wsCompleted && !exceptionThrown) 
     { 
      // The exception is being thrown. 
      exceptionThrown = true; 
      throw new Exception(); 
     } 
    } 
}; 

// Set up the callback on the web service. 
ws.GetRequestCompleted += 
    delegate(object sender,WS.GetRequestCompletedEventArgs e) { 
     // Dispose of timer when done. 
     using (t) 
     // Lock. 
     lock (l) 
     { 
      // The web service call has completed. 
      wsCompleted = true; 

      // If the timer completed and the exception was 
      // not thrown, then do so here. 
      if (timerCompleted && !exceptionThrown) 
      { 
       // The exception is being thrown. 
       exceptionThrown = true; 
       throw new Exception(); 
      } 
     } 

     // Handle callback. 
    }; 

// Start the timer, make the web service call. 
t.Start(); 
ws.GetRequest("Login","Username","Password"); 

需要注意以下幾點:

  • 你必須在這兩個計時器回調和Web服務的回調,以檢查其他條件有得到滿足,如果該異常有被拋出。你不想拋出異常兩次。
  • 您沒有指出如何獲取例外回給用戶。現在,這個異常將在除調用線程之外的其他線程上拋出。這將導致用戶非常難看的例外。
  • Timer實例的處理在回調Web服務處理。這假設web服務的回調將總是完成,是否成功。
+0

我所做的是在計時器到達結束時停止Web服務,或者在Web服務完成時停止計時器,並在getcomplete事件內部添加回調。 – Janub 2012-03-20 09:58:08