3

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

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

这是代码:-

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);
        }
    }
}

如果你能帮助我,我会感谢你的支持

4

3 回答 3

2

好的,因为您使用的是 .Net 3.5,所以不能使用 .Net 4.0 引入的 TPL。

STA 线程与否,在您的情况下,有一种比WaitAll. 你可以简单地拥有一个 counter 和一个 unique 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();
}

另外仅供参考,ThreadPool.QueueUserWorkItem每次调用时都不会产生一个线程(我说这是因为评论“为块中的每个项目产生一个线程”)。它使用一个线程池,因此它主要重用现有线程。

于 2013-04-16T17:21:46.087 回答
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();
}
于 2013-12-14T11:25:52.640 回答
0

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

你可以在这里找到它:http ://www.nuget.org/packages/TaskParallelLibrary

也许这会有所帮助。

于 2013-12-14T12:05:52.900 回答