Reputation: 13843
Let's say I have a function
public void SendMessage(Message message)
{
// perform send message action
}
Can I create a delegate for this kind of function? If so, how can I pass a message when I use the delegate?
In my case, the function is used by Thread. Whenever there is an event, I need to send a message to the server, to keep the record. I also need to keep it running in background, so that it won't affect the application. However, the threading needs to use delegate
Thread t = new Thread(new ThreadStart(SendMessage));
and I don't know how to pass the message into the delegate. Thanks.
Upvotes: 4
Views: 378
Reputation: 360
You can also do thing like that
object whatYouNeedToPass = new object();
Thread t = new Thread( () =>
{
// whatYouNeedToPass is still here, you can do what ever you want :)
});
t.Start();
Upvotes: 0
Reputation: 4079
You need to use a ParametizedThreadStart. See here:
http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx
Upvotes: 2
Reputation: 62027
sure, just define the delegate that way:
delegate void SendMessageDelegate(Message message);
Then just invoke it as normal:
public void InvokeDelegate(SendMessageDelegate del)
{
del(new Message());
}
Upvotes: 3
Reputation: 754725
Sure
public delegate void DelWithSingleParameter(Message m);
Passing a message can be done with the following
DelWithSingleParameter d1 = new DelWithSingleParameter(this.SomeMethod);
d1(new Message());
Also as @Mehrdad pointed out in newer versions of the framework you no longer need to define such delegates. Instead reuse the existing Action<T>
delegate for this type of operation.
Action<Message> d1 = new Action<Message>(this.SomeMethod);
d1(new Message());
Upvotes: 11