c# - 如果第一个代码正在执行,如何等待?

标签 c# .net multithreading asynchronous async-await

我遇到一种情况,当用户单击 tabitem 时,用户会创建类的实例。这个类包含一个绘制图表的函数,它非常耗时,所以它是异步编写的。

现在的问题是,假设用户第一次单击选项卡,类实例化,这个漫长的过程会持续很长时间,同时之前的异步任务没有完成,用户再次单击同一个选项卡。

在这种情况下,我必须等到前一个异步任务未完成,然后第二次单击 tabitem 时必须在第一个异步任务完成后创建实例(它应该等到第一个异步进程未完成)。

代码在这里:

if (selectedTabIndex == 2) //What is the user selected second time whil the previous task is still not finshed ? 
{         
    DrawGraph obj= new DrawGraph(selectedItem.Name);
 }   

我在 DrawGraph 类构造函数中的某个地方完成了:

 public DrawGraph(string Name)
 {
   timeConsumingProcess(Name);
 }

 public async void timeConsumingProcess(string Name)
 {       
   await  startTaimeConsumingProcess();
 }

我想要的是,当用户第二次单击此选项卡项目编号=2时,它必须等到上一个异步任务完成,然后它必须再次实例化 DrawGraph 类 再次重新启动异步。

如何实现?

最佳答案

In this situation i must wait until the previous async task is not finished and then on second click to tabitem must create instance after teh fist async task is finshed

然后让您的代码 (a)等待最后一个任务:

private Task drawGraph = null;
...
if (selectedTabIndex == 2)
{
  if (drawGraph != null)
    await drawGraph;
  DrawGraph obj = new DrawGraph(selectedItem.Name);
  drawGraph = obj.timeConsumingProcess();
}

...

private readonly string name;
public DrawGraph(string Name)
{
  name = Name;
}

public async Task timeConsumingProcess()
{
  await  startTaimeConsumingProcess();
}

请注意,这要求您使用 async Task 而不是 async void,无论如何,这都很好,因为您应该 avoid async void .

关于c# - 如果第一个代码正在执行,如何等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42415294/

相关文章:

Java - 中断线程?

Java 每月计时器

c++ - 为什么在死锁的情况下 lock() 不抛出异常

c# - 创建 Thickness() 时如何使用合格的 Double?

c# - 在 Windows UWP 应用程序中使用 Python 和 C#

c# - 进程交互(c#和纯c++)

c# - 如何在 ColdFusion 中使用 C#.NET 程序集?

c# - 从 Windows 服务托管的 WCF 端点的问题

c# - 为什么 Cast() 不调用构造函数?

mysql - 周期性 MySql 超时,然后是 ASP.NET 网站中的连接峰值