【问题标题】:C# threadpooling troubleC#线程池问题
【发布时间】:2012-05-25 08:30:42
【问题描述】:

我是线程新手,所以如果我的问题属于业余水平,请原谅我。下面的示例是我正在尝试做的简化版本。如果方法 go 是静态的,则此方法有效,我希望它在 Go 非静态时有效。如何让它发挥作用。

using System;
using System.Threading;
using System.Diagnostics;



public class ThreadPoolExample
{
    static void Main()
    {

           for (int i = 0; i < 10; i++)
           {

               ThreadPool.QueueUserWorkItem(Go, i);
           }
           Console.ReadLine(); 



    }

     void Go(object data)    
    {

        Console.WriteLine(data); 
    }
}

如果有人可以完成这项工作并添加所有线程已完成执行的通知,那就太棒了。

【问题讨论】:

    标签: c# threadpool


    【解决方案1】:

    我怀疑这与 Go 是否为静态无关,而是您不能从静态“Main”调用/使用实例方法“Go”这一事实。两者都需要是静态的,或者您需要在您的类的实例上调用/使用 Go,例如:

    ThreadPool.QueueUserWorkItem(value => new ThreadPoolExample().Go(value), i);
    

    【讨论】:

    • 嗯,是的,除了你的(正确的)解决方案确实实际上与Go 是静态的有关。 ;)
    【解决方案2】:

    这样做

    class ThreadPoolExample
    {
          static void Main(string[] args)
        {
    
             for (int i = 0; i < 10; i++)
            {
                ThreadPoolExample t = new ThreadPoolExample();
                ThreadPool.QueueUserWorkItem(t.Go, i);
    
            }
            Console.ReadLine(); 
        }
    
         void Go(object data)    
        {
    
            Console.WriteLine(data); 
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-23
      • 2020-10-02
      • 2020-11-21
      • 1970-01-01
      • 2011-02-27
      • 2017-07-08
      • 1970-01-01
      相关资源
      最近更新 更多