2016-08-10 6 views
0

私はWPF MainWindow ctorで異常な動作をしています。私は長いタスクを作るために非同期メソッドを使用していますが、このタスクは 'DoAsync'という名前で完了していません!私は回避策が見つかりましたが、コードが失敗した理由を私は理解していない:(ここでは、2つの呼び出しと結果を:?.net非同期異常動作

/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    static void WriteToOutput(string message, int increment = 0) 
    { 
     var nw = DateTime.Now; 
     var msg = string.Format("{0}.{1:d3} - thread {2:d1}[0x{3:x4}] |\t{4}{5}", 
            nw.ToString("hh:mm:ss"), 
            nw.Millisecond, 
            System.Threading.Thread.CurrentThread.ManagedThreadId, 
            AppDomain.GetCurrentThreadId(), 
            new string(' ', 4 * increment), 
            message 
           ); 

     System.Diagnostics.Debug.WriteLine(msg); 
    } 

    public async Task DoAsync() 
    { 
     WriteToOutput("DoAsync: begin", 2); 
     await Task.Delay(1);     // enforces asynchronism 
     WriteToOutput("DoAsync: job begin", 3); 
     System.Threading.Thread.Sleep(5000); // simulates some job ;) 
     WriteToOutput("DoAsync: job end", 3); 
     WriteToOutput("DoAsync: end", 2); 
    } 

    private void NormalBehavior() 
    { 
     WriteToOutput("NormalBehavior: begin", 0); 

     Task.Run(async() => 
     { 
      WriteToOutput("NormalBehavior_DoAsync: begin", 1); 
      await DoAsync(); 
      WriteToOutput("NormalBehavior_DoAsync: end", 1); 
     }); 

     WriteToOutput("NormalBehavior: sleeping", 0); 
     System.Threading.Thread.Sleep(10000);  // to see what happens 
     WriteToOutput("NormalBehavior: terminated", 0); 
    } 

    /// <summary> 
    /// Seems the simplest solution, but it fails :(Why ? 
    /// </summary> 
    private void AbnormalBehavior() 
    { 
     WriteToOutput("AbnormalBehavior: begin", 0); 

     WriteToOutput("AbnormalBehavior_DoAsync: begin", 1); 
     var tsk = DoAsync(); 
     WriteToOutput("AbnormalBehavior_DoAsync: end", 1); 

     WriteToOutput("AbnormalBehavior: sleeping", 0); 
     System.Threading.Thread.Sleep(10000);  // to see what happens 
     WriteToOutput("AbnormalBehavior: terminated", 0); 
    } 

    public MainWindow() 
    { 
     NormalBehavior(); 
     // Output: 
     // 05:18:00.833 - thread 8[0x3818] | NormalBehavior: begin 
     // 05:18:00.842 - thread 8[0x3818] | NormalBehavior: sleeping 
     // 05:18:00.846 - thread 9[0x2274] |  NormalBehavior_DoAsync: begin 
     // 05:18:00.848 - thread 9[0x2274] |   DoAsync: begin 
     // 05:18:00.853 - thread 10[0x0778] |    DoAsync: job begin 
     // 05:18:05.855 - thread 10[0x0778] |    DoAsync: job end 
     // 05:18:05.856 - thread 10[0x0778] |   DoAsync: end 
     // 05:18:05.856 - thread 10[0x0778] |  NormalBehavior_DoAsync: end 
     // 05:18:10.843 - thread 8[0x3818] | NormalBehavior: terminated 
     //_________________________________________________________________ 

     AbnormalBehavior(); 
     // Output: 
     // 05:18:10.845 - thread 8[0x3818] | AbnormalBehavior: begin 
     // 05:18:10.846 - thread 8[0x3818] |  AbnormalBehavior_DoAsync: begin 
     // 05:18:10.847 - thread 8[0x3818] |   DoAsync: begin 
     // 05:18:10.849 - thread 8[0x3818] |  AbnormalBehavior_DoAsync: end 
     // 05:18:10.850 - thread 8[0x3818] | AbnormalBehavior: sleeping 
     // 05:18:20.853 - thread 8[0x3818] | AbnormalBehavior: terminated 
     //_________________________________________________________________ 

     InitializeComponent(); 
    } 
} 

誰もがすでにこの問題を見つけたかの説明があり

+0

結果を求めていないためです。 'var tsk = DoAsync();を作成します。 tsk.Result'。 – cassandrad

答えて

1

をあなたはそれを実行してみましょう場合もはや、私はあなたがDoWorkのデバッグウィンドウに 『仕事が始まる』と他のメッセージが表示されます期待し

async/awaitのためのこの予想される動作、特に、awaitは、現在の 『コンテキスト』をキャプチャします - 。。その中「異常な」ケースはUIコンテキストであり、その継続を再開する内線私はmechanics of async/awaitを私のブログで詳しく説明します。

このコードのもう1つの点は、Thread.Sleepが現在のスレッドをブロックしていることです。特に、Thread.SleepがUIスレッドで実行されると、そのスレッドはブロックされ、他のコードを実行することはできません。

Task.Runは、UIコンテキストが存在しないスレッドプールスレッドで指定されたコードを実行し、その場合はawaitはスレッドプールスレッドで再開します。

したがって、最初の(作業中の)例では、DoAsyncはスレッドプールスレッドで実行され、5秒間スレッドプールスレッドをブロックします。その間、NormalBehaviorはUIスレッドを10秒間ブロックします。

第2の(失敗した)例では、AbnormalBehaviorはUIスレッドでDoAsyncを実行します。 DoAsyncawaitに達するとすぐにAbnormalBehaviorが実行され、UIスレッドは10秒間ブロックされます。そのときだけ、DoAsyncがUIスレッドで再開して5秒間ブロックすることができます。

0

スティーブンは、「AbnormalBehavior」の最後のスリープの後、「DoAsync:job begin」と表示されます&「DoAsync:job end」がすべてメインスレッドによって行われました! 効果的には、すべての作業を行う同じスレッド(メインスレッド)で、寝ている間は '仕事'をすることはできません。 私がコンソールプログラムで期待したように、さらに同じコードが実行されています!あなたがこのケースで見るように、それは仕事をする他のスレッド(ワーカースレッド)です!おそらく、それはコンテキストをキャプチャする必要はありません!

class Program 
{ 
    static DateTime _Start = new DateTime(0); 

    static void WriteToOutput(string message, int increment = 0, bool start = false) 
    { 
     var nw = DateTime.Now; 
     if (start) _Start = nw; 
     var spn = nw - _Start; 

     var msg = string.Format("{0,2:d}.{1:d3} - thread {2,2:d1}[0x{3:x4}] |\t{4}{5}", 
            (int)Math.Floor(spn.TotalSeconds), 
            spn.Milliseconds, 
            System.Threading.Thread.CurrentThread.ManagedThreadId, 
            AppDomain.GetCurrentThreadId(), 
            new string(' ', 4 * increment), 
            message 
           ); 

     if (start) msg = "\n" + msg; 
     //System.Diagnostics.Debug.WriteLine(msg); 
     Console.WriteLine(msg); 
    } 

    public static async Task DoAsync() 
    { 
     WriteToOutput("DoAsync: begin", 2); 
     await Task.Delay(1);     // enforces asynchronism 
     WriteToOutput("DoAsync: job begin", 3); 
     System.Threading.Thread.Sleep(5000); // simulates some job ;) 
     WriteToOutput("DoAsync: job end", 3); 
     WriteToOutput("DoAsync: end", 2); 
    } 

    /// <summary> 
    /// It works correctly but it uses more resources and run more slowly :o 
    /// </summary> 
    /// <returns></returns> 
    public static Task DoRescueAsync() 
    { 
     WriteToOutput("DoAsync: begin", 2); 
     return Task.Run(() => { 
      WriteToOutput("DoAsync: job begin", 3); 
      System.Threading.Thread.Sleep(5000); // simulates some job ;) 
      WriteToOutput("DoAsync: job end", 3); 
      WriteToOutput("DoAsync: end", 2); 
     }); 
    } 

    private static void NormalBehavior() 
    { 
     WriteToOutput("NormalBehavior: begin", 0, true); 

     Task.Run(async() => 
     { 
      WriteToOutput("NormalBehavior_DoAsync: begin", 1); 
      await DoAsync(); 
      WriteToOutput("NormalBehavior_DoAsync: end", 1); 
     }); 

     WriteToOutput("NormalBehavior: sleeping", 0); 
     System.Threading.Thread.Sleep(10000);  // to see what happens 
     WriteToOutput("NormalBehavior: terminated", 0); 
    } 

    /// <summary> 
    /// Seems the simplest solution, but it fails :(Why ? 
    /// </summary> 
    private static void AbnormalBehavior() 
    { 
     WriteToOutput("AbnormalBehavior: begin", 0, true); 

     WriteToOutput("AbnormalBehavior_DoAsync: begin", 1); 
     var tsk = DoAsync(); 
     WriteToOutput("AbnormalBehavior_DoAsync: end", 1); 

     WriteToOutput("AbnormalBehavior: sleeping", 0); 
     System.Threading.Thread.Sleep(10000);  // to see what happens 
     WriteToOutput("AbnormalBehavior: terminated", 0); 
    } 

    static void Main(string[] args) 
    { 
     NormalBehavior(); 
     // Output: 
     // 0.000 - thread 1[0x34cc] | NormalBehavior: begin 
     // 0.014 - thread 1[0x34cc] | NormalBehavior: sleeping 
     // 0.019 - thread 3[0x0bdc] |  NormalBehavior_DoAsync: begin 
     // 0.024 - thread 3[0x0bdc] |   DoAsync: begin 
     // 0.029 - thread 4[0x1568] |    DoAsync: job begin 
     // 5.045 - thread 4[0x1568] |    DoAsync: job end 
     // 5.050 - thread 4[0x1568] |   DoAsync: end 
     // 5.053 - thread 4[0x1568] |  NormalBehavior_DoAsync: end 
     // 10.018 - thread 1[0x34cc] | NormalBehavior: terminated 
     //_________________________________________________________________ 

     AbnormalBehavior();  // now CORRECT as expected ! 
     // Output: 
     // 0.000 - thread 1[0x34cc] | AbnormalBehavior: begin 
     // 0.008 - thread 1[0x34cc] |  AbnormalBehavior_DoAsync: begin 
     // 0.029 - thread 1[0x34cc] |   DoAsync: begin 
     // 0.037 - thread 1[0x34cc] |  AbnormalBehavior_DoAsync: end 
     // 0.043 - thread 1[0x34cc] | AbnormalBehavior: sleeping 
     // 0.047 - thread 3[0x0bdc] |    DoAsync: job begin 
     // 5.062 - thread 3[0x0bdc] |    DoAsync: job end 
     // 7.306 - thread 3[0x0bdc] |   DoAsync: end 
     //10.057 - thread 1[0x34cc] | AbnormalBehavior: terminated 
     //_________________________________________________________________ 

     Console.Write("\nHit a key to close console: "); Console.ReadKey(); 
    } 
} 
関連する問題