防止执行异步方法[关闭]

问题描述 投票:-4回答:1

我有两个主要方法和一个UI方法,例如:

Method1,它支持互斥结构或一类数组

void Method1(){
   // ORM & Database readings code goes here
 }

void Method2(){ dim x as integer } x不是互斥为什么?

不是method3()调用method2()_ mutex :: monitor ??为什么?

c# .net wpf async-await
1个回答
1
投票

我建议在这种情况下使用SemaphoreSlim来避免轮询。

ctor()
{
  // Initialize the semaphore.
  this.semaphore = new SemaphoreSlim(1, 1);
}

public async void Button_Click(object sender, EventArgs args)
{
  await Method2Async();
}

private async Task Method2Async()
{
  await this.semaphore.WaitAsync();
  ICalculationResult result = await CalculateAsync(); // Do your calculations and then continue
  await Method1Async(result);

  this.semaphore.Release();
}

private async Task Method1Async()
{
  // Async Method1 implementaion
}

private async Task<ICalculationResult> CalculateAsync()
{
  await Task.Run(()=> 
    {
      return new ICalculationResult();  // Do the calculation and return the result
    });
} 
© www.soinside.com 2019 - 2024. All rights reserved.