Blazor Startup Error: System.Threading.SynchronizationLockException: Cannot wait on monitors on this runtime

时光总嘲笑我的痴心妄想 提交于 2020-12-13 04:08:16

问题


I am trying to call an api during the blazor(client side) startup to load language translations into the ILocalizer.

At the point I try and get the .Result from the get request blazor throws the error in the title.

This can replicated by calling this method in the program.cs

  private static void CalApi()
    {
        try
        {
            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(@"https://dummy.restapiexample.com/api/v1/employees");
            string path = "ididcontent.json";
            string response = httpClient.GetStringAsync(path)?.Result;
            Console.WriteLine(response);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error getting api response: " + ex);
        }

    }

回答1:


Avoid .Result, it can easily deadlock. You get this error because the mechanism is not (cannot be) supported on single-threaded webassembly. I would consider it a feature. If it could wait on a Monitor it would freeze.

private static async Task CalApi()
{
   ... 
   string response = await httpClient.GetStringAsync(path); 
   ...
}

All events and lifecycle method overrides can be async Task in Blazor, so you should be able to fit this in.




回答2:


In Program.cs

 public static async Task Main(string[] args)
 {

    ......

    builder.Services.AddSingleton<SomeService>();

    var host = builder.Build();       

    ...

call your code here but use await

    var httpClient = host.Services.GetRequiredService<HttpClient>();
    string response = await httpClient.GetStringAsync(path);
    ...

    var someService = host.Services.GetRequiredService<SomeService>();
    someService.SomeProperty = response;

    await host.RunAsync();



回答3:


This is a example best:

var client= new ProductServiceGrpc.ProductServiceGrpcClient(Channel);
            category =  (await client.GetCategoryAsync(new GetProductRequest() {Id = id})).Category;



来源:https://stackoverflow.com/questions/63211539/blazor-startup-error-system-threading-synchronizationlockexception-cannot-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!