当我执行按钮单击事件并在打开时写入文本文件时,它仍然挂起 UI 线程的任何原因。在写完之前不能做任何事情。
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"/>
有什么理由吗?