不支持在sta线程上使用多个句柄的waitall

时间:2013-04-16 16:48:15

标签: c# multithreading exception

大家好,我运行我的应用程序时遇到此异常。 我在.net 3.5上工作,所以我不能使用Task

  

不支持在sta线程上使用多个句柄

这是代码: -

private void ThreadPopFunction(ContactList SelectedContactList, List<User> AllSelectedUsers)
{
        int NodeCount = 0;

        AllSelectedUsers.EachParallel(user =>
        {
            NodeCount++;
            if (user != null)
            {
                if (user.OCSEnable)
                {
                    string messageExciption = string.Empty;
                    if (!string.IsNullOrEmpty(user.SipURI))
                    {
                        //Lync.Lync.Lync lync = new Lync.Lync.Lync(AdObjects.Pools);
                        List<Pool> myPools = AdObjects.Pools;
                        if (new Lync.Lync.Lync(myPools).Populate(user, SelectedContactList, out messageExciption))
                        {
                        }
                    }
                }
            }
        });
}

这是我用来处理多线程的扩展方法

public static void EachParallel<T>(this IEnumerable<T> list, Action<T> action)
{
    // enumerate the list so it can't change during execution
    // TODO: why is this happening?
    list = list.ToArray();
    var count = list.Count();

    if (count == 0)
    {
        return;
    }
    else if (count == 1)
    {
        // if there's only one element, just execute it
        action(list.First());
    }
    else
    {
        // Launch each method in it's own thread
        const int MaxHandles = 64;
        for (var offset = 0; offset <= count/MaxHandles; offset++)
        {
            // break up the list into 64-item chunks because of a limitiation in WaitHandle
            var chunk = list.Skip(offset*MaxHandles).Take(MaxHandles);

            // Initialize the reset events to keep track of completed threads
            var resetEvents = new ManualResetEvent[chunk.Count()];

            // spawn a thread for each item in the chunk
            int i = 0;
            foreach (var item in chunk)
            {
                resetEvents[i] = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(new WaitCallback((object data) =>
                {
                    int methodIndex =
                        (int) ((object[]) data)[0];

                    // Execute the method and pass in the enumerated item
                    action((T) ((object[]) data)[1]);

                    // Tell the calling thread that we're done
                    resetEvents[methodIndex].Set();
                }), new object[] {i, item});
                i++;
            }

            // Wait for all threads to execute
            WaitHandle.WaitAll(resetEvents);
        }
    }
}

如果您能帮助我,我将非常感谢您的支持

3 个答案:

答案 0 :(得分:2)

好的,当您使用.Net 3.5时,您无法使用.Net 4.0中引入的TPL。

STA线程与否,在您的情况下,有一种比WaitAll更简单/有效的方法。你可以简单地拥有一个计数器和一个唯一的WaitHandle。这是一些代码(现在无法测试,但应该没问题):

// No MaxHandle limitation ;)
for (var offset = 0; offset <= count; offset++)
{
    // Initialize the reset event
    var resetEvent = new ManualResetEvent();

    // Queue action in thread pool for each item in the list
    int counter = count;
    foreach (var item in list)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback((object data) =>
                      {
                          int methodIndex =
                              (int) ((object[]) data)[0];

                          // Execute the method and pass in the enumerated item
                          action((T) ((object[]) data)[1]);

                          // Decrements counter atomically
                          Interlocked.Decrement(ref counter);

                          // If we're at 0, then last action was executed
                          if (Interlocked.Read(ref counter) == 0)
                          {
                              resetEvent.Set();
                          }
                      }), new object[] {i, item});
    }

    // Wait for the single WaitHandle
    // which is only set when the last action executed
    resetEvent.WaitOne();
}

同样FYI,ThreadPool.QueueUserWorkItem每次调用时都不会产生一个线程(我之所以说这是因为注释“为块中的每个项目生成一个线程”)。它使用一个线程池,因此它主要重用现有的线程。

答案 1 :(得分:0)

对于像我这样的人,谁需要使用这些例子。 ken2k的解决方案非常好,它可以正常工作,但有一些更正(他说他没有测试它)。这是ken2k的工作示例(为我工作):

// No MaxHandle limitation ;)
for (var offset = 0; offset <= count; offset++)
{
    // Initialize the reset event
    var resetEvent = new ManualResetEvent(false);

    // Queue action in thread pool for each item in the list
    long counter = count;
    // use a thread for each item in the chunk
    int i = 0;
    foreach (var item in list)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback((object data) =>
                      {
                          int methodIndex =
                              (int) ((object[]) data)[0];

                          // Execute the method and pass in the enumerated item
                          action((T) ((object[]) data)[1]);

                          // Decrements counter atomically
                          Interlocked.Decrement(ref counter);

                          // If we're at 0, then last action was executed
                          if (Interlocked.Read(ref counter) == 0)
                          {
                              resetEvent.Set();
                          }
                      }), new object[] {i, item});
    }

    // Wait for the single WaitHandle
    // which is only set when the last action executed
    resetEvent.WaitOne();
}

答案 2 :(得分:0)

实际上有一种方法可以在.net 3.5中使用(至少很好的一部分)TPL。有一个为Rx-Project完成的后端。

您可以在此处找到它:http://www.nuget.org/packages/TaskParallelLibrary

也许这会有所帮助。