Hi VM,
"VM" <vo******@yahoo.com> wrote in message
news:es**************@TK2MSFTNGP09.phx.gbl...
I'm trying to add multithreading to my win application but I'm having
trouble with the code since the method to be threaded has parameters. How
can I add multithreading to a method with parameters? MSDN says
ThreadStart cannot take parameters, so how can I do it?
public System.Threading.Thread Thread_LoadAZM;
public void LoadFile(string sFileName)
{
Thread_LoadAZM=System.Threading.Thread(new
System.Threading.ThreadStart(this.loadAuditFile)); //error
Thread_LoadAZM.Start();
}
private void loadAuditFile(string sFileName)
{
....
}
Another option (which, frankly, I'm surprised doesn't get more "press")
is to use a custom delegate. So within your class you might have a delegate
declared like this:
private delegate void LoadFileHandler(string sFileName);
Then, to call the LoadFile method on another thread, you could use code
like this:
...
LoadFileHandler handler = new LoadFileHandler(this.LoadFile);
handler.BeginInvoke(someFileName, null, null);
...
The BeginInvoke method is generated automatically by the compiler from
the delegate declaration. BeginInvoke has all the parameters defined by the
delegate plus one for passing a callback delegate and one for passing a
"state" parameter. Besides making the parameter passing much easier, the
above also has the advantage of using the thread pool, which is usually a
better idea than creating your own threads.
Regards,
Daniel