I’m calling an async method which is located in App.xaml.cs file. I’m calling this method from my c# file of home page (HomePageView.xaml.cs). I don’t know why but I’m getting this error:
System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'
This exception is thrown on the line starting with TEXT1_STRING
.
The UpdateText()
method is:
private async void UpdateText()
{
HomePageViewText1.Text = "error text";
TEXT1_STRING = Task.Run(() => App.GetJSONAsync()).Result;
return;
}
GetJSONAsync()
method code can be found below:
internal static async Task<string> GetJSONAsync()
{
string JSON = null;
using HttpClient client = new HttpClient();
try
{
JSON = await client.GetStringAsync("https://www.example.com/api/getdata");
}
catch (Exception e)
{
log.Error("Error fetching JSON" + e.ToString());
}
return JSON;
}
Can anyone help me why this is happening? I’m not very familiar with Threading, Marshals etc. with C#. Thank you.
2
Answers
I've solved this exception by applying @M.M's solution. What I did was to return
TEXT1_STRING = Task.Run(() => App.GetJSONAsync()).Result;
toTEXT1_STRING = await App.GetJSONAync();
After this change, the exception was not thrown and program was able to build and run successfully.
Fixed version of
UpdateText()
:The first function should be:
As an
async
function it should contain anawait
statement . Trying to make an async function run synchronously, by usingTask(....).Result()
or otherwise, is a bit of a minefield, see this blog for some explanation.See also async/await – when to return a Task vs void? — exception handling is different for
async void
functions thanasync Task
functions.