9

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....

4

3 回答 3

16

像这样将事件添加到您的库中:

public event Action<string> OnDataReceived = null;

然后,在应用程序中:

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

而已。

但是您可能希望使用约定编写事件,我建议您开始习惯它,因为 .NET 就是这样使用事件的,所以每当您遇到该约定时,您就会知道它是事件。因此,如果我稍微重构您的代码,它应该是这样的:

在您的类库中:

//...
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" });
   }
}

当您的类库想要启动事件时,它应该调用 OnDataReceived,它负责检查是否有人正在侦听并构造适当的 EventArgs 以将您的数据传递给侦听器。

在应用程序中,您应该更改您的方法签名:

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

//...

void ReceivedData(object sender, YourEventArgs e)
{
  string data = e.Data;
  //...
}
于 2013-05-11T06:24:02.960 回答
2

您应该更改 start 方法的签名以传递委托:

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....
}
于 2013-05-11T06:20:13.077 回答
0

将活动添加到您的班级

public event DataReceivedEventHandler DataReceived;
public delegate void DataReceivedEventHandler(object sender, SocketDataReceivedEventArgs e);

创建一个包含所需参数的类,例如 Ex :SocketDataReceivedEventArgshere

触发事件如

SocketDataReceivedEventArgs DataReceiveDetails = new SocketDataReceivedEventArgs();
DataReceiveDetails.data = "your data here";
DataReceived(this, DataReceiveDetails);

在应用程序创建方法中

void receivedData(object sender, SocketDataReceivedEventArgs e)
{
    // e.data is data which received by library....
}

现在将处理程序附加到它

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

您需要在多个线程中编写它,因为您的要求是这里是如何在上面添加线程安全支持

Dispatcher.Invoke 并从另一个线程访问文本框

于 2013-05-11T06:28:18.970 回答