如何在c#中从库到应用程序生成回调(事件)

本文关键字:程序生成 应用 回调 事件 | 更新日期: 2023-09-27 18:13:01

我正在开发一个库(DLL),其中我需要向用户提供事件(中断)作为一个具有数据的方法。库的工作是在套接字上开始列表,从套接字接收数据,并通过一个方法将数据传递给用户。

库:

public void start(string IP, int port)
{
    // start logic...
    // receives data from socket... send this data to user
}
应用:

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

如何使用库中的数据向应用程序引发事件?

Thanks in advance....

如何在c#中从库到应用程序生成回调(事件)

像这样添加一个事件到库中:

public event Action<string> OnDataReceived = null;

然后,在Application中:

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

您应该更改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....
}

添加事件到您的类

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

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

触发类似

的事件
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);

您需要根据需要在多个线程中编写它下面是如何为上面的

添加线程安全支持的方法

调度员。从另一个线程调用和访问文本框