Problem with my Async/Await implementation
Hi everyone,
I'm encountering some persistent issues with my async and await implementation in a UWP application. I'm trying to perform a network request and update the UI, but I'm facing a System.InvalidOperationException saying "The application called an interface that was marshalled for a different thread."
Here's a simplified version of my code:
public async Task LoadDataAsync()
{
try
{
var data = await GetDataFromApiAsync();
// Problematic UI update here?
MyTextBlock.Text = data.Result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error: {ex.Message}");
}
}
private async Task<ApiResponse> GetDataFromApiAsync()
{
// ... network request logic ...
await Task.Delay(1000); // Simulate network latency
return new ApiResponse { Result = "Data loaded successfully!" };
}
I've tried using await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ... }); but it doesn't seem to resolve the issue reliably. Any suggestions on how to correctly handle UI updates from async operations in UWP?
Thanks in advance!