开发者

How to use ThreadPool.QueueUserWorkItem with non-static methods?

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 ConsoleApplicat开发者_如何学Pythonion1

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


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).


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜