2017-01-11 27 views
-1

嗨我已閱讀其他教程,但無法弄清楚。我正在運行一項任務,當任務完成時,我想隱藏當前窗體並加載另一個窗體,但它掛起並沒有顯示任何內容。這是我的代碼,請引導我 -C#停止Form_Show()中的任務()

public Loading() 
 
{ 
 
     InitializeComponent(); 
 
     Shown += Loading_Shown; 
 
} 
 
private void Loading_Shown(object sender, EventArgs e) 
 
{ 
 
     label2.Text = "Step 1..."; 
 
     Task.Run(() => 
 
     { 
 
      if (Directory.Exists(contentPath)) 
 
      { 
 
       filePresent = false; 
 
      } 
 

 
      if (filesPresent == false) 
 
      { 
 
       BeginInvoke(
 
       (MethodInvoker)delegate 
 
        { 
 
         label2.Text = "Downloading Files..."; 
 
        } 
 
       ); 
 

 
       Directory.CreateDirectory(contentPath); 
 
       Home form = new Home(); 
 
       form.Visible = true; 
 
      } 
 

 
      else 
 
      { 
 
        Home form = new Home(); 
 
        form.Visible = true; 
 
      } 
 
     }); 
 
}

另一種形式負載半屏幕掛起。請指導我如何繼續這一點。謝謝

+0

您正在運行任務的同期,而不是異步這樣的代碼將阻塞,直到任務完成。 – jdweng

回答

4

你不創建第二個窗體「當[任務]完成」,但裏面的那個任務。因此,您在與第一個不同的線程上創建第二個窗體。這是一個壞主意。

一個解決方案是使Loading_Shownasync方法和await的任務。然後,當任務真的已經完成和控制流返回到原來的UI線程,你可以創建第二個表格:

private async void Loading_Shown(object sender, EventArgs e) 
{ 
    label2.Text = "Step 1..."; 
    await Task.Run(() => 
    { 
     // different thread 
     filePresent = Directory.Exists(contentPath); 
     if (!filePresent) Directory.CreateDirectory(contentPath); 
    }); 

    // back on UI thread 
    if (!filesPresent) 
    { 
     label2.Text = "Downloading Files..."; }); 

     Home form = new Home(); 
     form.Visible = true; 
    } 
    else{ 
     Home form = new Home(); 
     form.Visible = true; 
    } 
}