简体   繁体   中英

How to avoid a task to block the main thread?

Suppose you have the following code:

Action action = () =>
{
  MethodThatReadSomeDataFromExternalHardware();
};

Task.Run(action);

The MethodThatReadSomeDataFromExternalHardware() method connects to a hardware device and return some data.

Which kind of device is not relevant to the problem.

Now, if that hardware is disconnected, the MethodThatReadSomeDataFromExternalHardware() methodh get stuck trying to connect.

Well... the problem is that when that method is stuck, the main thread is also stuck, until the hardware timeout occur.

Is there a way to avoid this? Of course, that is only one atomic method, so I cannot add inside it a loop or something in order to allow message processing in the main thread.

I suspect it is not possible but I am wondering if there is some C# instruction or Windows API to launch a parallel task that does not affect the main thread if that child process get stuck.

Regard Jaime

Don't use Tasks

If you just want the method to complete and don't care whatever happens with the result -or- you are fine dealing with it in another thread; don't use Tasks as they are heavier than the thread pool , and require .Net 4.5 .

Use the Thread Pool

It may be a bit old and less fancy than TPL but it fits the bill. You use the ThreadPool much the same way you use Task . Instead of calling Run you call QueueUserWorkItem :

ThreadPool.QueueUserWorkItem(_ => {
   MethodThatReadSomeDataFromExternalHardwareAsync();
});

That way you enjoy both the lighter weight ThreadPool and your code is much more portable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM