【发布时间】:2020-05-06 15:38:37
【问题描述】:
我试图在一个 cs 类中调用一个异步方法,但页面只是冻结了。
调试时,一切似乎都运行良好,直到 await thing.wait.WaitAsync(); 行。在该行之后,没有其他断点被命中(我周围有一堆断点,包括下一行的一个),页面看起来一直在加载,并且没有弹出错误/异常消息。
ApiClient_Test.razor
@if (myResult == null)
{
<p><em>Loading...</em></p>
}
else
{
<p>@myResult</p>
}
@code{
private string myResult;
protected override async Task OnInitializedAsync()
{
var test = new ApiClient_BlazorTest.ApiClientBlazorTests.ApiClient_TestAsync();
myResult = test.MyMethod();
}
}
ApiClientTest.cs
namespace ApiClient_BlazorTest.ApiClientBlazorTests
{
public class ApiClient_TestAsync : Controller
{
public string MyMethod()
{
var a = MyAsyncMethod();
a.Wait();
return a.Result;
}
public async Task<string> MyAsyncMethod()
{
var thing = new athing();
// start a thing that takes 6 seconds
thing.dothings();
// await the thing
await thing.wait.WaitAsync();
return "ok";
}
private class athing
{
public SemaphoreSlim wait { get; set; } = new SemaphoreSlim(1);
public string dothings()
{
wait.Wait();
Task.Run(() => { Thread.Sleep(6000); wait.Release(); });
return "";
}
}
}
}
我在控制台应用程序上运行了相同的代码。那里一切正常。
以前有人见过类似的 blazor 和 async 函数吗?
【问题讨论】:
-
控制台应用在异步方面非常不同。
标签: c# asynchronous client blazor