(The entire previous post in the comments).
My new understanding is that you have 3 types of tasks.
You would like these three to be as parallel as possible, but you will also like Reader if he wants to go into port scanning so as not to do this while the scanner port is alive. One way to solve this problem is Semaphore . Semaphores control access to a limited amount of resources.
In your case, you have a limited amount (actually only 1) of resources ("port scan"). In this case, we could choose a simpler AutoResetEvent . However, I feel that Semaphore can actually reduce confusion.
// Only 1 task may port scan at a time Semaphore portScanResource = new Semaphore(initialCount: 1, maximumCount: 1); // ... // "Reader task" var task = Task.Factory.StartNew( () => { // ... if (shouldPortScan) { portScanResource.WaitOne(); try { // do your port scan } finally { // we're done portScanResource.Release(); } } });
The Port Scanner task will use the same Semaphore , ensuring that only one thread scans ports at a time.
source share