简体   繁体   English

如何在C#中使用Tasks.Parallel停止现有任务

[英]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 ? 如何使用.Net中的Parallel库实现此目的?

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 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. 如果您使用异步Socket API,则无需担心为监听的Socket扩展单独的线程...更不用说它围绕性能的同步调用运行了很多时间。

Food for thought ... 令人回味的食物...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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