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

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

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

此时我尝试从 get 请求中获取 .Result blazor 在标题中抛出错误。

这可以通过在 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 不支持(不能)支持该机制。我会认为这是一个功能。如果它可以在监视器上等待,它就会冻结。

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

所有事件和生命周期方法覆盖都可以在 Blazor 中 async Task,因此您应该能够适应它。

在Program.cs

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

    ......

    builder.Services.AddSingleton<SomeService>();

    var host = builder.Build();       

    ...

在此处调用您的代码但使用 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();

这是最好的例子:

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