在C#中多次并行执行方法的最佳方法是什么 [英] What would be best approach to execute a method multiple times parallel in C#

查看:101
本文介绍了在C#中多次并行执行方法的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想从这里的专家那里得到一些建议。

我需要在连接到我系统的设备上运行一些测试。我的应用程序应该一次为所有连接的设备并行运行测试方法,并从每个设备获得结果。我已经编写了一个测试方法,我可以在其中传递设备ID,并在完成每个设备的测试后需要获得测试结果。



请让我知道哪个是实现这个的更好方法。在我的情况下,这个过程是同步的,我正在使用C#/ WPF。



我尝试过:



Hi,

I would like to get some advice from the experts here on one of my requirements.
I need to run some tests on the devices which are connected to my system. My application should run the test method parallel for all the connected devices at a time and get result from each device. I have written a method for the test in to which I can pass the device id and need to get the test result after completion of each device's test.

Please let me know which would be the better way to implement this. The process is synchronous in my case and I am using C#/WPF.

What I have tried:

public data[] SomeMethod()
{
  return Enumerable.Range(0, 10)
      .AsParallel().AsOrdered()
      .Select(DeviceTestMethod).ToArray();
}

推荐答案

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

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

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


           }
       }

   }


这篇关于在C#中多次并行执行方法的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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