developer747
developer747

Reputation: 15958

C# threadpooling trouble

I am new to threading, so please forgive me if my question is at an amateur level.The example below is a simplified version of what I am trying to do. This works if method go is static, I want it to work when Go is not static. How do I make it work.

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

If someone can make this work and add a notification that all threads have completed execution, that would be awesome.

Upvotes: 2

Views: 83

Answers (2)

Md Kamruzzaman Sarker
Md Kamruzzaman Sarker

Reputation: 2407

Do it in this way

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

}

Upvotes: 4

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

I suspect there it has nothing to do with Go being static or not, but rather the fact that you can't call/use instance method "Go" from static "Main". Either both need to be static or you need to call/use Go on an instance of your class like:

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

Upvotes: 5

Related Questions