启动多个线程和跟踪他们从我的.NET应用程序 [英] Starting multiple threads and keeping track of them from my .NET application

查看:113
本文介绍了启动多个线程和跟踪他们从我的.NET应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的.NET应用程序启动的线程x个,我想,让他们跟踪我将需要手动或者当我的应用程序关闭我的应用程序以后。

I would like to start x number of threads from my .NET application, and I would like to keep track of them as I will need to terminate them manually or when my application closes my application later on.

为例==>启动线程阿尔法,启动线程测试..然后在我的应用程序的任何一点,我应该可以说终止线程测试版。

Example ==> Start Thread Alpha, Start Thread Beta .. then at any point in my application I should be able to say Terminate Thread Beta ..

什么是跟踪打开线程在.NET中的最佳途径,什么才是我需要知道的(一个id?)关于线程终止了吗?
示例代码,教程将是有益的。

What is the best way to keep track of opened threads in .NET and what do I need to know ( an id ? ) about a thread to terminate it ? Sample code, tutorial would be helpful.

推荐答案

您可以保存自己的驴工作和使用的 智能线程池 。它提供的工作系统,使您可以查询每个线程的状态在任何点,并终止他们的单位。

You could save yourself the donkey work and use this Smart Thread Pool. It provides a unit of work system which allows you to query each thread's status at any point, and terminate them.

如果这是太花心,那么作为提及的的IDictionary<字符串,螺纹> 可能是最简单的解决方案。或者也可以简单的就是给每个线程的名字,并使用的IList<主题>

If that is too much bother, then as mentioned anIDictionary<string,Thread> is probably the simplest solution. Or even simpler is give each of your thread a name, and use an IList<Thread>:

public class MyThreadPool
{
    private IList<Thread> _threads;
    private readonly int MAX_THREADS = 25;

    public MyThreadPool()
    {
        _threads = new List<Thread>();
    }

    public void LaunchThreads()
    {
        for (int i = 0; i < MAX_THREADS;i++)
        {
            Thread thread = new Thread(ThreadEntry);
            thread.IsBackground = true;
            thread.Name = string.Format("MyThread{0}",i);

            _threads.Add(thread);
            thread.Start();
        }
    }

    public void KillThread(int index)
    {
        string id = string.Format("MyThread{0}",index);
        foreach (Thread thread in _threads)
        {
            if (thread.Name == id)
                thread.Abort();
        }
    }

    void ThreadEntry()
    {

    }
}

当然,你可以得到很多更多地参与复杂吧。如果杀死你的线程不敏感的时间(例如,如果你不需要杀死在3秒在UI线程),那么的Thread.join()是一个更好的做法。

You can of course get a lot more involved and complicated with it. If killing your threads isn't time sensitive (for example if you don't need to kill a thread in 3 seconds in a UI) then a Thread.Join() is a better practice.

如果你尚未阅读它,然后乔恩斯基特有这种良好的讨论,解决方案因为这是常见的SO不使用中止的建议。

And if you haven't already read it, then Jon Skeet has this good discussion and solution for the "don't use abort" advice that is common on SO.

这篇关于启动多个线程和跟踪他们从我的.NET应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆