关闭多线程应用程序 [英] Shutting down a multithreaded application

查看:131
本文介绍了关闭多线程应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写我的C#应用​​程序ThreadManager。我创建多个线程:结果
一个线程我的文字的作家。结果
一个线程监视的一些统计数据。结果
多个线程执行计算大序列(每核心4线程,我跑我的2倍四核服务器上的应用程序)。

I'm trying to write a ThreadManager for my C# application. I create several threads:
One thread for my text writer.
One thread that monitors some statistics.
Multiple threads to perform a large sequence of calculations (up to 4 threads per core and I run my app on a 2x quad core server).

我的应用程序正常运行在一个时间长达24小时,让所有的线程获得创建之初,他们在整个时间的应用程序运行依然存在。

My application normally runs for up to 24 hours at a time, so all the threads get created in the beginning and they persist through the entire time the app runs.

我想有一个地方,我注册我所有的胎面,当应用程序被关闭,我只是调用一个方法,它遍历所有注册的线程和关闭下来。

I want to have a single place where I "register" all of my treads and when the application is shutting down I simply invoke a method and it goes through all of the registered threads and shuts them down.

有关为此我设计了以下类:

For that purpose I have devised the following class:

public class ThreadManager
{
    private static Object _sync = new Object();
    private static ThreadManager _instance = null;
    private static List<Thread> _threads;
    private ThreadManager()
    {
        _threads = new List<Thread>();
    }

    public static ThreadManager Instance
    {
        get
        {
            lock (_sync)
            {
                if (_instance == null)
                {
                    _instance = new ThreadManager();
                }
            }
            return _instance;
        }
    }

    public void AddThread(Thread t)
    {
        lock (_sync)
        {
            _threads.Add(t);
        }
    }

    public void Shutdown()
    {
        lock (_sync)
        {
            foreach (Thread t in _threads)
            {
                t.Abort(); // does this also abort threads that are currently blocking?
            }
        }
    }
}

我要确保我的所有线程都杀了那么应用程序可以正常关闭,并在一些计算中间的关停只是罚款了。我应该知道的事情吗?这是很好的做法给予我的情况?

I want to ensure that all of my threads are killed so the application can close properly and shutting down in the middle of some computation is just fine too. Should I be aware of anything here? Is this approach good given my situation?

推荐答案

如果您设置线程后台线程,当应用程序被关闭,他们将被杀死。

If you set the threads to background threads, they will be killed when the application is shut down.

myThread.IsBackground = true;

很明显,如果你需要的线程关闭之前完成,这是不是你想要的解决方案。

obviously if you need the threads to finish before shutdown, this is not the solution you want.

这篇关于关闭多线程应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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