Working with synchronous operations (such like a file read) inside UWP application's main UI thread
Posted: (EET/GMT+2)
In UWP applications, the UI thread must stay responsive, or the user sees the application to "lock up". Thus, any blocking operation, such as a synchronous file read of a large file, can freeze the interface and cause the dreaded "App not responding" message. UWP enforces this by limiting what you can do on the UI thread.
The first rule is to use asynchronous APIs wherever possible. For example, to read a file, you could say:
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/data.txt"));
string text = await FileIO.ReadTextAsync(file);
MyTextBlock.Text = text;
If you absolutely must run a blocking call (for example, a legacy library API call), move it off the UI thread with Task.Run:
await Task.Run(() =>
{
var result = LegacyLibrary.ReadSomethingSynchronously();
// process result here...
});
The rule of thumb in UWP: if it can block, it belongs on a background thread. Keep the UI thread purely for updates and user interaction. You can find Microsoft's documentation on the topic here.