爲什麼當我執行按鈕單擊事件並在打開文本文件時寫入文本文件的任何原因仍然是掛起UI線程。寫作完成之前無法做任何事情。在Windows 8中寫入文件時的異步
private async void WriteFileClick(object sender, RoutedEventArgs e)
{
string fileName = @"asyn3cfile.txt";
string text = "Hello async, this was written while you were doing something else in the UI";
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
var writtenFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream randomAccessStream = await writtenFile.OpenAsync(FileAccessMode.ReadWrite))
{
Stream stream = randomAccessStream.AsStreamForWrite();
stream.Seek(0, SeekOrigin.Begin);
WriteFileTextAsync(text, stream);
await stream.FlushAsync();
await randomAccessStream.FlushAsync();
}
Debug.WriteLine("{0} was created", fileName);
}
private async static void WriteFileTextAsync(string text, Stream stream)
{
for (int i = 0; i < 100; i++)
{
var fileText = string.Format("{0} in process {1}\n", text, i);
byte[] textBytes = Encoding.UTF8.GetBytes(fileText);
stream.SetLength(stream.Length + textBytes.Length);
await stream.WriteAsync(textBytes, 0, textBytes.Length);
new System.Threading.ManualResetEvent(false).WaitOne(100);
}
}
XAML
<Button x:Name="WriteFileInDocumentsButton" Content="Write a text file" Click="WriteFileClick"/>
任何原因?
你能告訴你如何/在哪裏調用這些方法嗎?也許某處你有阻止主線程的任務的等待電話? –
它是通過按鈕事件點擊調用的。 –