Blazor invoke JS from synchronous method

Viewed 294

I have a piece of code in an Action that is querying a JS funtion.

Unfortunately I didn't make my registered action async at first and realized that the following code was stuck at the InvokeAsync line

async Task someCode() {
    string myRes = await jsRuntime.InvokeAsync<string>("MyMethod");
    Console.WriteLine(myCode); // <- this line was not reached!
}

public void myAction() {
    // synchronous here => how to convert it to synchronous code?!
    someCode.GetAwaiter().Result();
}

Because of this, the WriteLine part of code was not reached... Is there a proper way to call the async method here from the synchrounous method? Can anyone clarify why the following code works :

public async Task myAction() {
    await someCode;
}
1 Answers

I think that you have a sort of deadlock, change myAction:

public void myAction() {

 var result = someCode.ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();
}
Related