简体   繁体   中英

How to stop an existing task using Tasks.Parallel in c#

What I am looking to do is as follows:

1. Start TCP socket listener on another thread (so it does not block my app.)
2. Start 1..n other processes on other threads which will send data to my listener
3. Stop my listener when all of the other processes have finished.

How would I achieve this using the Parallel library in .Net ?

I presume I need to keep a reference to the initial spawned thread somehow and terminate it when a counter has been reached or something?

What about using a child / parent tasks:

From

http://msdn.microsoft.com/en-us/library/dd537609.aspx

var parent = Task.Factory.StartNew(() =>
{
    Console.WriteLine("Parent task beginning.");

    var child = Task.Factory.StartNew(() =>
    {
        Thread.SpinWait(5000000);
        Console.WriteLine("Attached child completed.");
    }, TaskCreationOptions.AttachedToParent);

});

parent.Wait();
Console.WriteLine("Parent task completed.");

/* Output:
    Parent task beginning.
    Attached task completed.
    Parent task completed.
 */

If you use the asychronous Socket API you will not have to worry about spinning up separate threads for your listening Sockets ... not to mention it runs circles around the sychronous calls on performance.

Food for thought ...

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