2014-02-18 23 views
0

在Windows應用商店項目IM工作的我有這段代碼的文件app.xaml.cs等待在Windows商店應用,如預期

...   
      DoStuff(); 



       // Place the frame in the current Window 
       Window.Current.Content = rootFrame; 
      } 
      if (rootFrame.Content == null) 
      { 
       // When the navigation stack isn't restored navigate to the first page, 
       // configuring the new page by passing required information as a navigation 
       // parameter 
       rootFrame.Navigate(typeof(SomePage), e.Arguments); 
      } 

,並在DoStuff功能某些操作後不工作,我稱之爲另一個稱爲InsertDB的函數。

private async void InsertDB(RootObject obj) 
    { 
     await Task.Run(() => obj.InsereDB()); 
    } 

這是幹什麼的,是將一些數據插入sqlite數據庫。 現在我的問題是,當我開始我的應用程序數據庫開始填充,我可以看到,因爲我看着我的項目的LocalState文件夾內的文件,並且sqlite文件開始增長的大小,但在它完成獲取我的視圖(「SomePage」)中的數據被加載。

不應該等待任務阻止視圖加載,直到「obj.InsereDB」函數返回?

回答

2

它沒有等待,因爲InsertDBasync void方法,這意味着,從來電者的角度來看,它將運行同步直到它遇到第一個await關鍵字。一旦完成,它將返回給調用者。

拍下這一刻:

private async void InsertDB(RootObject obj) 
{ 
    Console.WriteLine(1); 
    await Task.Run(() => obj.InsereDB()); 
    Console.WriteLine(2); 
} 

InsertDB(obj); 
Console.WriteLine(3); 

這段代碼打印1 3 2。當InsertDB命中await關鍵字時,它返回給調用者,該調用者打印出3.該方法的其餘部分異步運行。

您需要讓InsertDB返回一個任務,並等待它。

private async Task InsertDB(RootObject obj) 
{ 
    Console.WriteLine(1); 
    await Task.Run(() => obj.InsereDB()); 
    Console.WriteLine(2); 
} 

await InsertDB(obj); 
Console.WriteLine(3); 

這將打印1 2 3

+0

啊,是的,這似乎更好地工作確實,甚至寫了的Debug.WriteLine()看到它,它可以打印1 2 3,但是,我inicial「問題「仍然保留,它仍然在任務結束之前加載視圖。 – Ric

+0

@Ric你將不得不等待'DoStuff'以及 – dcastro

+0

耶啊,我注意到在你回答eheh之前,謝謝你的幫助:) – Ric