0

I am monitoring devices, using the example code below, and all works fine. The question is about how to handle each process at the same time. Let me explain.

When monitoring devices, we have an event that gets fired whenever a device disconnect. If for example we have to wait for each device to restart, or to reconnect to network, we use a thread.sleep() before starting the next commands. Only issue is if we have a large number of devices, each device will be done one at the time, potentially taking a long time to complete all devices. In this example, with a 10 seconds sleep, only 6 devices can be done every minutes..

How should I go to start 1 separate process for each device, and run it (almost) simultaneously? Or?

monitor.DeviceDisconnected += this.OnDeviceDisconnected;

private void OnDeviceDisconnected(object sender, DeviceDataEventArgs e)
{
    ......

    Thread.Sleep(10000);

    ......
}
Franck E
  • 629
  • 8
  • 26
  • 3
    Never call Thread.Sleep in the main thread of a UI application, as it blocks the thread and hence the UI. If you need to wait, use `await Task.Delay` instead. – Clemens May 14 '20 at 14:25
  • 1
    You need to look into the [Task Parallel Library](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl) for asynchronous programming. Follow the link and read through the documentation and you'll see how you need to proceed. – Nik P May 14 '20 at 14:29
  • There's a lot of question here but what you are looking for is Asynchronous programming. I recommend Tim Corey's YouTube videos as a great place to start: https://youtu.be/2moh18sh5p4 – George Kerwood May 14 '20 at 15:00

1 Answers1

1

I would assume that the event is raised on the main thread since the UI freezes. As @Clemens mentions, you should avoid using Thread.Sleep since this will block the thread, and this is quite disrupting if done on the main thread.

To use await the method needs to be marked with async. Async methods need to either return a Task, Task<T> or void. It is generally recommended to return a Task since this lets the caller know when the method completes and if any exceptions occurred.

Since it is an event handler the caller would not care when the task completes, but we should take care to not lose any exceptions . So the method signature would look something like this

private async voidOnDeviceDisconnected(object sender, DeviceDataEventArgs e){
{
    ......
    try{
        await Task.Delay(TimeSpan.FromSeconds(10));
        ....
     }
     catch(Exception e){
         // Handle exception
     }
}
JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Thanks Jonas, this was somehow useful to highlight a typo I made.. I set the delay to 1000 instead of 10000.. And did not understand why so fast... :) – Franck E May 14 '20 at 15:30
  • 2
    That's one reason why it's better to write something like `Task.Delay(TimeSpan.FromSeconds(10))` rather than just `Task.Delay(n)`. – Peregrine May 14 '20 at 15:51