Actually, in .NET 2.0, there is a ParameterizedThreadStart method which
takes an object parameter that you can pass to it. It's not really needed,
since you can use anonymous delegates in C# 2.0 to get around that.
However, I'll start with .NET 1.1 and before first. In that case, you
want to create a class:
public class FooSendInvoker
{
// The parameter to pass to send.
private Message message;
public FooSendInvoker(Message message)
{
this.message = message;
}
// Called by the thread.
public void Invoke()
{
// Make the call.
Foo.FooSend(message);
}
}
Then, in your code, you would do this:
// Create the invoker, passing the message.
FooSendInvoker invoker = new FooSendInvoker(message);
// Create the thread.
Thread t = new Thread(new ThreadStart(invoker.Invoke));
// Run.
t.Start();
In .NET 2.0, you can declare a method like this:
public static void FooSendInvoker(object message)
{
// Cast to a message.
Message m = (Message) message;
// Make the call.
Foo.FooSend(m);
}
And then in your code, you can use the ParameterizedThreadStart
delegate, like so:
Thread t = new Thread(FooSendInvoker);
// Call, passing the message.
t.Start(message);
But, C# 2.0 also makes it much easier to call the delegate, since you
can do this:
Thread t = new Thread(
delegate()
{
// Just make the call.
FooSend(message);
});
// Run the thread.
t.Start();
The message variable will be passed along to the method on the thread
and executed.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
<kp******@gmail.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
I want to call a method passing a parameter. I want to do this call on
a seperate thread. For example,
public class Foo
{
public static void FooSend(Message message)
{
// Start a seperate thread to call Send(message) method
// everytime someone calls this FooSend method
}
private static void Send(Message message)
{
// send the message
}
}
I know the threadstart delegate takes only methods that has no
arguments. But in my case I want to pass a parameter to the method
call.
Can someone help me here? Thanks.