I have the following method, which I want to run using WaitCallBack delegate (C# Thread-Pooling) technique:
public void ExportData(string data){
//Codes goes in here
}
how to use ThreadPool.QueueUserWorkItem(new WaitCallback(ExportData),object}
in order to call this method??
Some options:
string
and castUse a lambda expression instead, e.g.
ThreadPool.QueueUserWorkItem(ignored => ExportData(value))
where I assume value
is a string variable in scope at the time. This will create a new delegate instance each time you go through this code, to capture value
.
A combination of the above:
ThreadPool.QueueUserWorkItem(x => ExportData((string) x), value)
This will (potentially) reuse the same delegate instance on every call, as the value is passed via the normal WaitCallback
instead of being captured by the delegate.
Additionally, you might want to consider using the rather more modern Task
API unless you're targeting an old version of .NET. It's a generally more pleasant way of scheduling and managing tasks.
See more on this question at Stackoverflow