考虑 Blazor WebAssembly App(ASP.NET Core 托管)“空”项目。我调整了 Counter 页面如下:
<button class="btn btn-primary" @onclick="IncrementCountAsync">Click me</button>
Run Code Online (Sandbox Code Playgroud)
及其 Counter.razor.cs 文件:
public partial class Counter
{
private static int currentCount = 0;
private async Task IncrementCountAsync()
{
Console.WriteLine("Increment called");
_ = HeavyComputeAsync();
currentCount++;
Console.WriteLine($"Counter = {currentCount}");
}
private static Task<int> HeavyComputeAsync()
{
return Task.Run(() =>
{
Console.WriteLine("Task start");
for (long ndx = 0; ndx < 1000000; ++ndx)
ndx.ToString();
Console.WriteLine("Task end");
return 0;
});
}
}
Run Code Online (Sandbox Code Playgroud)
我将HeavyComputeAsync方法称为_ = ...,它不应等到IncrementCountAsync方法完成,而应立即更新currentCount …
我正在尝试定期运行一段代码,时间间隔介于两者之间.可能有多个此类代码块同时运行,因此我转而Task.Run使用异步方法调用和并行性.现在我想知道我应该如何实现时间间隔!
直截了当的方式是这样使用Task.Delay:
var t = Task.Run(async delegate
{
await Task.Delay(1000);
return 42;
});
Run Code Online (Sandbox Code Playgroud)
但是我想知道这样做是不是正确的方法,因为我相信所有的Task.Delay工作都是睡眠线程并在周期结束后恢复它(即使我不确定).如果是这种情况,则即使任务未运行,系统也必须为任务的线程资源付费.
如果是这种情况,有没有办法在一段时间后运行任务而不浪费任何系统资源?