Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate callback (event) from library to application in c#

Tags:

c#

oop

events

dll

I'm developing one library (DLL), in which I need to provide event (interrupt) to user as one method with data. Library's work is start listing on socket, receive data from socket and pass this data to user in one method.

Library:

public void start(string IP, int port)
{
    // start logic...

    // receives data from socket... send this data to user

}

Application:

Library. Class a = new Library. Class();
a.start(ip, port);

// I need this method called by library automatically when it receives data...

void receivedData(string data)
{
    // data which received by library....
}

How to raise event to application with data from library?

Thanks in advance....

like image 853
Never Quit Avatar asked May 11 '13 05:05

Never Quit


2 Answers

Add an event to your library like this:

public event Action<string> OnDataReceived = null;

Then, in Application:

Library.Class a = new Library.Class();
a.OnDataReceived += receivedData;
a.start(ip, port);

That's it.

But you may want to write events with the conventions and I suggest you'll start get use to it because .NET is using events that way so whenever you bump into that convention you'll know it's events. So if I refactor your code a little bit it should be something like:

In your class library:

//...
public class YourEventArgs : EventArgs
{
   public string Data { get; set; }
}
//...

public event EventHandler DataReceived = null;
...
protected override OnDataReceived(object sender, YourEventArgs e)
{
   if(DataReceived != null)
   {
      DataReceived(this, new YourEventArgs { Data = "data to pass" });
   }
}

When your class library wants to launch the event it should call the OnDataReceived which is responsible for checking that someone is listening and constructing the appropriate EventArgs for passing by your data to the listener.

In the Application you should change your method signature:

Library.Class a = new Library.Class();
a.DataReceived += ReceivedData;
a.start(ip, port);

//...

void ReceivedData(object sender, YourEventArgs e)
{
  string data = e.Data;
  //...
}
like image 90
graumanoz Avatar answered Nov 14 '22 00:11

graumanoz


You should change signature of start method to pass there delegate:

public void start(string IP, int port, Action<string> callback)
{
    // start logic...

    // receives data from socket... send this data to user
    callback(data);
}

Library. Class a = new Library. Class();
a.start(ip, port, receivedData);

// I need this method called by library automatically when it receives data...

void receivedData(string data)
{
    // data which received by library....
}
like image 24
Kirill Bestemyanov Avatar answered Nov 14 '22 00:11

Kirill Bestemyanov