本文介绍了Blazor启动错误:System.Threading.SynchronizationLockException:无法在此运行时上等待监视器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在blazor(客户端)启动期间调用api,以将语言翻译加载到ILocalizer中.

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

这时,我尝试从get请求中获取.blazor的结果会在标题中引发错误.

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

这可以通过在程序中调用此方法来复制.cs

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);
        }

    }

推荐答案

避免使用 .Result ,它很容易死锁.您会收到此错误,因为单线程Webassembly不支持该机制.我认为这是一个功能.如果可以等待监视器,它将冻结.

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);
   ...
}

在Blazor中,所有事件和生命周期方法的替代都可以是 async Task ,因此您应该能够适应它.

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

这篇关于Blazor启动错误:System.Threading.SynchronizationLockException:无法在此运行时上等待监视器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 04:08