嵌套异步/等待函数 [英] Nesting async/await functions

查看:159
本文介绍了嵌套异步/等待函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示,使用异步/等待多任务的最佳方法是什么:



semicode:



as follow ,what's the best methods for use async/await for Multiple Task :

semicode:

public class Process
{
   public Process()
   {
       this.ProcessItem();
   }
}

  private async void ProcessItem()
   {
       while (true)
       {
           await this.FetchDeviceData(); //Read From Devices
           await Task.Delay(2000);   //300000
           await this.Process(); //Insert Into DataBase
       }
   }

   private async Task FetchDeviceData()
   {
       await Task.Run(() =>
       {
        //Read From all Devices;
       }
   }

  private async Task Process()
  {
     if (!(await RDataBase.ProcessItem(Mem,Date)))
         //Update Record;
  }

        //---------------------- RDataBase Class

  public static async Task<bool> ProcessItem(int Memb, int Date)
     {
       return await Task.Run(() =>
        {
            try
            {
            //Array List = Read Device Info From DataBase
            return True;
            }
            catch
            {
          return false;
            }
        });
     }





我尝试过:



我在申请中调用Global.ascx中的流程类实例ation_Start()方法。



What I have tried:

I Call the Instance Of Process Class in Global.ascx in the Application_Start() method.

推荐答案

这是你可以实现我想你想要做的一种方式。



Here is one way you could achieve what I think you are wanting to do.

 var tasks = new List<Task>();

 tasks.Add(Task.Factory.StartNew(() =>
{
   // add long running task here - 1
}));
				
 tasks.Add(Task.Factory.StartNew(() =>
{
   // add long running task here - 2
}));

Task.WaitAll(tasks.ToArray());





你可以替换Task.Factor.StartNew使用异步方法调用。



You could replace Task.Factor.StartNew with async method calls.


这篇关于嵌套异步/等待函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆