且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中多次并行执行方法的***方法是什么

更新时间:2021-10-20 22:39:08

我会使用 async await 异步运行测试的框架。

代码设备能够运行 TestDevice $ c的类$ c>异步方法。类似的东西。

I would use the async await framework to run the tests asynchronously.
Code a Device class that is able to run the TestDevice method asynchronously. Something like.

public class Device
   {
       public async Task<Data[]> TestDeviceAsync()
       {
           //run the TestDevice method asynchronously
           return await Task.Run(() => TestDevice());
       }

       private Data[] TestDevice()
       {
           //test device and return results
           return new Data[6];
       }

   }

然后实例化 TestManager 用于运行所需测试的类。

Then instantiate a TestManager class to run the required tests.

public class TestManager
   {
       public async Task TestDevicesAsync()
       {
           var tasks = new List<Task<Data[]>>();
           for (int i = 0; i < 6; i++)
           {
               var device = new Device();
               //start each task off but don't await it
               //tasks are started by simply invoking the async method
               Task<Data[]> task = device.TestDeviceAsync();
               tasks.Add(task);
           }
           //await  for all theTasks to finish
           Data[][] testResults = await Task.WhenAll(tasks);
           foreach (var dataArry in testResults)
           {
               //do something with the results


           }
       }

   }