Monday, July 29, 2013

Crash when calling Task.Result from UI-Thread

"You cannot call Task methods that block on the UI thread."

Is this documented anywere?


Here is another sample:



/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// works how i expect it to work
bool result = DoSomethingAsync().Result;

// works how i expect it to work
// this should be just the extended version of the statement above
Task<bool> task = DoSomethingAsync();
task.Wait();
result = task.Result;

// works fine because this is the nice standard way
//result = await DoSomethingAsync(); // add async to the signature to use this
}

private Task<bool> DoSomethingAsync()
{
return Task<bool>.Run( async () =>
{
await Test();
return true;
});
}

private async Task<bool> Test()
{
await Task.Delay(1000);
return true;
}



by actually creating a task i get the behavior i expected.





No comments:

Post a Comment