确保.Net Compact Framework 3.5 dll中的进程退出时完成后台线程

时间:2014-07-23 21:34:04

标签: .net multithreading compact-framework

我有一个dll,它有一个静态方法,客户端调用该方法将一些信息记录到各个目的地。此方法使用ThreadPool在另一个线程上启动日志记录工作。我需要一种方法来在进程退出之前可靠地确保这些线程完成。 AppDomains的ProcessExit事件在3.5 CF中不可用,那么我在哪里/如何可靠地等待这些线程完成?我能想到的唯一解决方案是使线程成为前台线程(线程上的工作是小而有限的),但在其他SO答案中已经建议这是不好的形式(但没有资格,所以不确定为什么)。

1 个答案:

答案 0 :(得分:0)

如上所述,使用state对象为线程池中启动的每个线程提供引用。使用事件处理程序来指示主进程,哪个线程已终止。

以下是使用控制台代码的简单示例:

using System;
using System.Threading;

namespace ThreadPoolTest
{
    class MainClass
    {
        static int intRest=256;
        static object lockObject=new object();
        public static void Main (string[] args)
        {
            bool bStop=false;
            Console.WriteLine ("Hello World!");
            work w=new work();
            //start about 256 threads using ThreadPool
            w.start();
            w.CounterReached+=count;
            do{
                Thread.Sleep(1000);
                lock(lockObject){
                    if(intRest==0)
                        bStop=true;
                }
            }while(!bStop);
            Console.WriteLine ("### Hello World END ###");
        }

        static void count(object sender, work.CounterEventArgs e){
            lock(lockObject){
                intRest--; //count down instead of checking which thread has terminated
            }
            Console.WriteLine("got event for " + e.counter.ToString());
        }
    }
    class work{

        public class CounterEventArgs : EventArgs
        {
            public int counter { get; set; }
            public CounterEventArgs(int i){
                counter=i;
            }
        }
        protected virtual void OnThresholdReached(CounterEventArgs e)
        {
            EventHandler<CounterEventArgs> handler = CounterReached;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public event EventHandler<CounterEventArgs> CounterReached;

        void threadStart(object o){
            int i = (int)o;
            System.Console.WriteLine("Thread: "+i.ToString()+" started");
            System.Threading.Thread.Sleep(1000);
            System.Console.WriteLine("Thread: "+i.ToString()+" ended");
            OnThresholdReached(new CounterEventArgs(i));
        }


        public void start(){
            for(int i=0; i<256; i++){
                WaitCallback w=new WaitCallback(threadStart);
                System.Threading.ThreadPool.QueueUserWorkItem(w, i);
            }
        }
    }
}

这里我开始新线程,直到达到256个线程。每个Waitcallback获取启动的线程数。主进程/线程在while循环(控制台应用程序)内等待,直到所有线程都完成。