首页 > 解决方案 > 我想知道为什么我的处理函数同时运行它的所有函数而不是相互等待?

问题描述

我想知道为什么我的处理函数同时运行它的所有函数而不是相互等待?

有人能告诉我为什么我的处理程序同时执行 func1 和 func2 吗?

我的方法 1 和方法 2 完美运行,它们在等待前一个完成时执行。但是当它执行处理程序时。

但是 func1 和 func2 同时异步运行。我怎样才能解决这个问题?

public void Run()
{
       lock (_theLock)
       {
             Task.Run(async () => {
                   await method1();
                   await method2();
                   await handler();
             });
       }
}

调用 func1 或 2 的处理程序方法:

private async Task handler() {
       await _timer.func1();
       await _timer.func2(); }

_timer 类:

   public class _timer

    public async void  func1()
    {
        lock (lock)
        {
            test1();          
        }
    }

    public async void func2()
    {
        lock (lock)
        {
            test2();
        }
    }

    public async Task test1()
    {
        await method1(); // the same method as in  the run method
    }

    public async Task test2()
    {
        await method2(); // the same method as in  the run method
    }

    public async Task method1()
    {
         var test1 = await GetDataFromSource1();
         await  doStuff(test1);
     }

   public async Task func2()
   {
        await method2(); // the same method as in  the run method
   }

   public async Task method2()
   {
         var test2 = await GetDataFromSource2();
         await  doStuff(test2);
   }

 public async Task<List<items>> GetDataFromSource1() {

 // retrieves data from database SQL

}

 public async Task<List<items>> GetDataFromSource2() {

 // retrieves data from database SQL    
}

 public async Task doStuff(List<string> items) {

 // does stuff with the data

}

标签: c#

解决方案


问题1:async void- 调用者无法知道它何时完成;使用async Taskorasync ValueTask代替;你几乎不应该使用async void.

问题 2:你await在调用test1or时没有test2,所以......什么都没有等待

问题 3:你不能使用lockwith await- 你需要使用不同的锁定原语,也许SemaphoreSlim(1,1)(它像互斥锁一样工作)

obersvation:这些代码实际上都不是真正的异步


推荐阅读