Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a delegate carry parameters?

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.

like image 287
jojo Avatar asked Dec 03 '22 13:12

jojo


2 Answers

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());
like image 138
JaredPar Avatar answered Dec 19 '22 11:12

JaredPar


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());
 }
like image 25
Matt Greer Avatar answered Dec 19 '22 10:12

Matt Greer