我正在编写一个 C# 桌面应用程序,该应用程序利用 dll(我编写的)从数据库中检索数据。
dll 具有多种功能,具体取决于用户想要的数据。我想更新应用程序 UI 上的标签,因为数据库功能在 dll 中完成。
我的代码布局如下:
应用:
private void getData(object sender, EventArgs e)
{
dll.DoDatabaseFunctions();
}
.DLL:
public static DataTable getThisStuff
{
//connections to SQL DB and runs command
//HERE is where I would like to send something back to the application to update the label
}
public static DataTable getThatStuff
{
//connections to SQL DB and runs command
//HERE is where I would like to send something back to the application to update the label
}
任何想法将不胜感激!
在 dll 类中创建一个可以在 GUI 中订阅的event
。
在 dll 中声明事件:
public event Action DataReady;
在需要时在 dll 中引发事件:
DataReady?.Invoke();
或
var dataReady = DataReady;
if (dataReady != null)
dataReady();
订阅 gui 中的事件:
dll.DataReady += OnDataReady;
引发事件时更新 gui 中的标签:
public void OnDataReady()
{
label.Text = "Whatever";
}
如果需要参数,可以将Action<T1,..,Tn>
用于事件。例如:
public event Action<string> DataReady;
DataReady?.Invoke("data");
dll.DataReady += OnDataReady;
public void OnDataReady(string arg1)
{
label.Text = arg1;
}
最后,在不再需要时取消订阅事件:
dll.DataReady -= OnDataReady;
您可以使用事件。在 dll 类中定义一个事件,并且您不能真正使用静态,因为您需要有一个实例(静态事件不是一个好主意)。
像这样:
private void getData(object sender, EventArgs e)
{
var dllInstance = new Dll();
dll.Updated += dllUpdateReceived;
dllInstance.DoDatabaseFunctions();
}
private void dllUpdateReceived(object sender, DllUpateEventArgs e)
{
var updateDescription = e.UpdateDescription;
// TODO: Update a label with the updates
}
以及 dll 项目中必要的东西:
public class DllUpdateEventArgs: EventArgs {
public string UpdateDescription { get; set; }
}
public class Dll {
public event EventHandler<DllUpdateEventArgs> Updated;
private void OnUpdated(string updateDescription) {
var updated = Updated;
if (updated != null) {
updated(this, new DllUpdateEventArgs { UpdateDescription = updateDescription });
}
}
public void DoDatabaseFunctions() {
// Do things
OnUpdated("Step 1 done");
// Do more things
OnUpdated("Step 2 done");
// Do even more things
OnUpdated("Step 3 done");
}
}