1

我似乎無法從Windows應用商店的後臺任務中讀取文件。下面是讀取文件內容的代碼:從Windows應用商店應用中的後臺任務訪問文件

async private static Task<string> ReadAsync(string FileName) 
{ 
    var folder = ApplicationData.Current.LocalFolder; 
    var file = await folder.GetFileAsync(FileName); 
    Windows.Storage.Streams.IRandomAccessStreamWithContentType inputStream = null; 
    try 
    { 
     inputStream = await file.OpenReadAsync(); 
    } 
    catch (Exception ex) 
    { 
     throw (ex); 
    } 
    string content = string.Empty; 
    using (Stream stream = inputStream.AsStreamForRead()) 
    { 
     using (StreamReader reader = new StreamReader(stream)) 
     { 
      try 
      { 
       // *** program exits on this line 
       content = await Task.Run(() => reader.ReadToEnd()); 
      } 
      catch(Exception ex) 
      { 
       // no error is caught 
       content = ex.Message; 
      } 
     } 
    } 

    return content; 
} 

上,關於StreamReader的調用ReadToEnd的()行退出程序 - 被夾在try catch塊沒有錯誤。在輸出窗口,我得到:

程序「[8968] backgroundTaskHost.exe:管理(v4.0.30319)」已退出,代碼爲1(爲0x1)

是否有可能訪問文件後臺任務?如果是這樣,我哪裏錯了?

+0

線了這些異常處理程序的,並告訴我們它是否提供任何更多的信息,以幫助排除故障: 'Application.ThreadException + =新ThreadExceptionEventHandler(ApplicationThreadException);'和' + AppDomain.CurrentDomain.UnhandledException =新UnhandledExceptionEventHandler(ApplicationUnhandledException) ;' –

+0

我不確定這些處理程序是否可用於WinRT?我已經嘗試將這些添加到App.xaml.cs,但編譯器無法識別它們 –

回答

7

如果您發佈了IBackgroundTask代碼,這將有所幫助。如果沒有看到它,我懷疑你沒叫GetDeferral()裏面,例如:

public async void Run(IBackgroundTaskInstance taskInstance) 
{ 
    var deferral = taskInstance.GetDeferral(); 
    var contents = await ReadAsync("MyFile.txt"); 
    deferral.Complete(); 
} 

你需要調用GetDeferral()當你正在你的後臺任務裏面異步調用。這樣,您告訴運行時,它需要等待異步調用完成,並在Run退出後立即停止後臺任務。

一旦大功告成,即通常在您Run方法的最後,你需要調用Complete()上推遲實例通知大功告成運行。

+0

Spot on!我沒有在我的IBackgroundTask中使用延期 –

-1

已經有系統類(DataReader)異步讀取文件,所以我不確定爲什麼你決定寫自己的。

相關問題