2017-10-29 20 views
0

メインウィンドウのコードに10秒ごとにタイマーが設定されています。 timer_Elapsedイベントで参照されるコードの中にはCPUを多少使用するものがあるため、await Task.Run(() =>の中に配置しましたが、経過したイベントが実行されるたびにUIスレッドは一時的にハングします。これがUIをブロックする理由は何ですか?コード:私の非同期タイマーがUIスレッドをブロックするのはなぜですか?

async void _timer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     await Task.Run(() => 
     { 
      //Update default status bar text routinely 
      try 
      { 
       if (ChecEnabled()) 
       { 
        this.Dispatcher.Invoke(() => 
        { 
         StatusText.Text = String.Format("Status: Enabled. Watching for changes…"); 
        }); 
       } 
       else 
       { 
        this.Dispatcher.Invoke(() => 
        { 
         StatusText.Text = String.Format("Status: Disabled"); 
        }); 
       } 
      } 
      catch (ObjectDisposedException) 
      { 
       //Window closed and disposed timer on different thread 
      } 

      //System Checks 
      UpdateSystemReadyStatus(); 
     }); 
    } 
+0

'ChecEnabled()'はCPU集約的な部分ですか?あなたはそのコードを投稿できますか? 'UpdateSystemReadyStatus'を表示しても良いでしょう。 – Enigmativity

+0

ちょうど明白である - 問題の原因となっている質問にこれまで示したコードには何もありません。私たちはあなたに良い答えを与えることができるように完全なコードを表示する必要があります。 – Enigmativity

+0

Timer.Elapsedハンドラでタスクを開始するのは意味がありません。 Timerはすでにバックグラウンドスレッドで実行されています。 – Clemens

答えて

3

InvokeInvokeAsyncに更新してください。また、実際にはTaskで包まれたメソッド全体を必要としますか?

async void _timer_Elapsed(object sender, ElapsedEventArgs e) 
{ 
    //Update default status bar text routinely 
    try 
    { 
     if (ChecEnabled()) 
     { 
      await this.Dispatcher.InvokeAsync(() => 
      { 
       StatusText.Text = String.Format("Status: Enabled. Watching for changes…"); 
      }); 
     } 
     else 
     { 
      await this.Dispatcher.InvokeAsync(() => 
      { 
       StatusText.Text = String.Format("Status: Disabled"); 
      }); 
     } 
    } 
    catch (ObjectDisposedException) 
    { 
     //Window closed and disposed timer on different thread 
    } 

    //System Checks 
    await Task.Run(()=>UpdateSystemReadyStatus()); 
} 
関連する問題