Home > database >  Calling a static async method from a Page results in InteropServices.COMException error
Calling a static async method from a Page results in InteropServices.COMException error

Time:12-20

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.

CodePudding user response:

The first function should be:

private async Task UpdateText()
{
    HomePageViewText1.Text = "error text";

    TEXT1_STRING = await GetJSONAsync();

    return;
}

As an async function it should contain an await statement . Trying to make an async function run synchronously, by using Task(....).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 than async Task functions.

CodePudding user response:

I've solved this exception by applying @M.M's solution. What I did was to return TEXT1_STRING = Task.Run(() => App.GetJSONAsync()).Result; to TEXT1_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():

private async void UpdateText()
{
    HomePageViewText1.Text = "error text";

    TEXT1_STRING = await App.GetJSONAync();
    
    return;
}
  • Related