2012-03-12 8 views
0

私はwsdlによって生成された関数を持っていますが、そのうちの1つはイベントも持つ非同期関数です。タイマーを非同期リクエストに設定する

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

私はGetRequestCompletedが発生しませんしばらくして、私はエラーメッセージが表示されます場合は、上記の要求のためのタイマーを作成したいです。 wsdl関数に変更するアクセス権がありません。

次の2つのことを行う必要があります

答えて

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

    関連する問題