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

北城以北 提交于 2019-12-14 02:35:32

问题


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

回答1:


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




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


来源:https://stackoverflow.com/questions/5786501/how-to-use-threadpool-queueuserworkitem-with-non-static-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!