私はWindows 10 Universal Appを開発しています。 RichEditBoxとListViewがあります。ユーザがListView項目をクリックするたびに、アプリケーションはRichEditBoxの実際のContentをrtfファイルに保存し、RichEditBoxに表示するために別のファイルからデータをロードする必要があります。 私にとって混乱を招くのは、UIコールのコンテキストでasycメソッドを処理する方法です。だから、そのタスクを達成するための "素晴らしい"コードは何でしょうか? 基本的には、最初にsaveメソッドを呼び出してからloadメソッドを呼び出すclickメソッドがあります。しかし...クリック方法は非同期でなければならないのでしょうか?ロード/セーブは非同期でなければなりません(通常、IO操作が待たれる必要があるため)。私はそれが何らかの理由でエラーFOREスローので、私の「解決策」は、完全ながらくたであることを推測WindowsストアアプリC#で:フィリ(非同期)からUIにデータをロードする方法は?
private void MasterListView_ItemClick(object sender, ItemClickEventArgs e)
{
// don't care that UI will not wait on completion
saveRtfFile("name");
loadRtfFile("name");
}
private async Task saveRtfFile(String filename)
{
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile isfStorageFile = await localFolder.GetFileAsync(filename);
if (isfStorageFile != null)
{
// Prevent updates to the remote version of the file until we
//finish making changes and call
Windows.Storage.CachedFileManager.DeferUpdates(isfStorageFile);
// write to file
Windows.Storage.Streams.IRandomAccessStream randAccStream = await isfStorageFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
MyRichEditBox.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);
// finished changing -> other app can update the file.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(isfStorageFile);
if (status != FileUpdateStatus.Complete)
{
Windows.UI.Popups.MessageDialog
errorBox = new Windows.UI.Popups.MessageDialog("File " + isfStorageFile.Name + " couldn't be saved.");
await errorBox.ShowAsync();
}
}
}
private async Task loadRtfFile(String filename)
{
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile rtfStorageFile = await localFolder.GetFileAsync(filename);
if (rtfStorageFile != null)
{
Windows.Storage.Streams.IRandomAccessStream randAccStream = await rtfStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
// Load the file into the Document property of the RichEditBox.
MyRichEditBox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, randAccStream);
}
}
:私が試した まず最初は、このでした。 clickメソッド内で非同期IOコールを処理する正しい方法は何ですか?
ありがとうございました!それはうまくいった。私はそのルールを念頭に置いておきます。 – quaxdachs