简体   繁体   中英

ThreadPool.QueueUserWorkItem Error when run method in separate thread in c# 2.0

i got a code to invoke any method through thread.

System.Threading.ThreadPool.QueueUserWorkItem(Export());

here i tried to run Export() method through thread and got compilation error. what is wrong in the code. i am using c# 2.0 version. please help.

QueueUserWorkItem takes a delegate, but you're calling the Export method and then trying to pass the result of Export to the QueueUserWorkItem method. In other words, it's as if you're running:

var result = Export();
ThreadPool.QueueUserWorkItem(result);

That's clearly not going to be running Export in another thread...

Assuming the signature of the Export method is correct, you just need to change it from a method invocation to a method group conversion:

ThreadPool.QueueUserWorkItem(Export);

EDIT: If you need to give arguments to the Export method, the simplest way of doing this is to use a lambda expression (assuming you're using C# 3). For example:

ThreadPool.QueueUserWorkItem(state => Export(filename));

Does method Export return a delegate of type WaitCallback ? If not then you're supplying the wrong parameter to QueueUserWorkItem . To be clear, you need to supply a delegate that conforms to the following signature:

public delegate void WaitCallback(
    Object state
)

So, method Export should have the following signature:

public void Export(object state)

and be supplied to QueueUserWorkItem as follows:

ThreadPool.QueueUserWorkItem(Export)

or, if Export has a different signature then you could use an intermediate delegate to call it:

ThreadPool.QueueUserWorkItem(state=>Export())

or if Export needs parameters, you could:

ThreadPool.QueueUserWorkItem(state=>Export(some,parameters))

You probably have to write ThreadPool.QueueUserWorkItem(new WaitCallback(Export)) and modifying export to have a single parameter of type object, ie:

Export(object state)
{
......

}

the state is a parameter you can pass-trought to the callback function when you call QueueUserWorkItem()

Providing Export matches the delegate that is to be supplied into QueueUserWorkItem do:

ThreadPool.QueueUserWorkItem(Export);

By writing Export() with parentheses you are calling the method instead of passing to QueueUserWorkItem to be called on a separate thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM