i got a code to invoke any method through t开发者_开发技巧hread.
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.
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))
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));
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.
加载中,请稍侯......
精彩评论