2

When I try to compile it gives me

Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.print(string)' ConsoleApplication1\ConsoleApplication1\Program.cs 15 47 ConsoleApplication1

So, I marked print as static and it works. But in a bigger program I have non-static methods. So how do I use ThreadPool with those methods?

class Program
{
    static void Main(string[] args)
    {
        ThreadPool.QueueUserWorkItem(o => print("hello"));
        Console.ReadLine();
    }

    public void print(string s)
    {
        Console.WriteLine(s);
    }
}

2 Answers 2

4

You just need an instance to operate on:

var myObject = new WhateverClassItIs();
ThreadPool.QueueUserWorkitem(o => myObject.SomeMethod("some input"));

Keep in mind that if the type that you use implements IDisposable (or some other cleanup mechanism), you should not invoke Dispose until you are certain that the asynchronous operation is completed (or at the end of the asynchronous operation itself).

Sign up to request clarification or add additional context in comments.

Comments

2

In order to call a non-static, you need an instance. For example, in your program, this would make it work:

class Program
{
   static void Main(string[] args)    
   {
       Program p = new Program();
       ThreadPool.QueueUserWorkItem(o => p.print("hello"));
       Console.ReadLine();
   }

   public void print(string s)
   {
      Console.WriteLine(s);    
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.