Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# threadpooling trouble

Tags:

c#

threadpool

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.

like image 697
developer747 Avatar asked Mar 14 '26 16:03

developer747


1 Answers

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);
like image 141
Alexei Levenkov Avatar answered Mar 17 '26 05:03

Alexei Levenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!