Click here to Skip to main content
15,895,831 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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();
}
Posted
Updated 11-Jan-18 11:09am

1 solution

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.


C#
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];
       }

   }

Then instantiate a TestManager class to run the required tests.


C#
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


           }
       }

   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900