.NET Threadpool使用AutoResetEvent进行同步

时间:2013-07-12 19:37:59

标签: c# .net multithreading threadpool

以下是我使用的代码。主线程等待Threadpool线程执行。我使用AutoResetEvent(WaitHandle),但我感到非常惊讶,因为代码没有按预期运行。

我有两个同心for循环,其中Threadpool在内循环中,并且预期对于外循环的每次迭代,应该处理所有内循环值。主线程使用内部循环外部的AutoResetEvent WaitOne调用等待,一个静态变量在外循环的每次迭代时重置为内循环的最大值,并使用Interlock在Threadpool线程上的方法调用中递减为AutoResetEvent调用Set。但是,即使我希望静态变量在每个内部循环后显示值0,它也不会。我的代码中的问题是什么,以及我完成任务的更好选择是什么?实际上,由于值的混淆,主线程似乎并没有真正等待Threadpool线程。

using System;
using System.Threading;

namespace TestThreads
{
class Program
{
    private static int threadingCounter = 0;
    private static readonly object lockThreads = new Object();
    private AutoResetEvent areSync = new AutoResetEvent(true);

    // <param name="args"></param>
    static void Main(string[] args)
    {
        Program myProgram = new Program();

        try
        {
            try
            {   
                for (int outer = 0; outer < 1000; outer++)
                {
                    threadingCounter = 500;
                    try
                    {
                        for (int inner = 0; inner < 500; inner++)
                        {
                            ThreadPool.QueueUserWorkItem(new
                                 WaitCallback(myProgram.ThreadCall), inner);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception :: " + ex.Message);
                    }
                    finally
                    {                            
                        myProgram.areSync.WaitOne();
                    }

                    if(threadingCounter != 0)
                        Console.WriteLine("In Loop1, Thread Counter :: " +
                            threadingCounter);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception :: " + ex.Message);
            }                
        }
        catch(Exception ex)
        {
            Console.WriteLine("Exception :: " + ex.Message);
        }
        finally
        {
            threadingCounter = 0;

            if (myProgram.areSync != null)
            {
                myProgram.areSync.Dispose();
                myProgram.areSync = null;
            }
        }
    }

    public void ThreadCall(object state)
    {
        try
        {
            int inner = (int)state;
            Thread.Sleep(1);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception :: " + ex.Message);
        }
        finally
        {
            Interlocked.Decrement(ref threadingCounter);
            if (threadingCounter <= 0)
                areSync.Set();
        }                
    }        
 }
}

2 个答案:

答案 0 :(得分:1)

您已初始化AutoResetEvent,初始状态为signaled(true),这将允许首次调用

myProgram.areSync.WaitOne();

继续没有阻塞,所以它继续外部循环和队列再次执行到Threadpool,因此结果搞砸了。很清楚。

将您的代码更新为

private AutoResetEvent areSync = new AutoResetEvent(false);

预期结果。希望这有帮助

答案 1 :(得分:0)

我会用这样的东西重构它。这假设您希望在内部循环中的后台线程中执行某些操作,在继续下一个外部循环之前完成每个操作,避免混乱的异常处理,同时仍然捕获处理期间发生的异常,以便您可以在处理后处理这些异常对于内循环和外循环都是完整的。

// track exceptions that occurred in loops
class ErrorInfo
{
    public Exception Error { get; set; }
    public int Outer { get; set; }
    public int Inner { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // something to store execeptions from inner thread loop
        var errors = new ConcurrentBag<ErrorInfo>();
        // no need to wrap a try around this simple loop
        // unless you want an exception to stop the loop
        for (int outer = 0; outer < 10; outer++)
        {
            var tasks = new Task[50];
            for (int inner = 0; inner < 50; inner++)
            {
                var outerLocal = outer;
                var innerLocal = inner;
                tasks[inner] = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            Thread.Sleep(innerLocal);
                            if (innerLocal % 5 == 0)
                            {
                                throw new Exception("Test of " + innerLocal);
                            }
                        }
                        catch (Exception e)
                        {
                            errors.Add(new ErrorInfo
                            {
                                Error = e,
                                Inner = innerLocal,
                                Outer = outerLocal
                            });
                        }
                    });
            }
            Task.WaitAll(tasks);
        }
        Console.WriteLine("Error bag contains {0} errors.", errors.Count);
        Console.ReadLine();
    }
}