c# - 从在 C# 中的单独线程上运行的外部类更新 Windows Form Control (listview)
问题描述
我有一个带有 ListView 控件的 Windows 窗体。我有另一个类“作业”,它在加载后被实例化并在这个表单的单独线程上执行。当类执行某些操作时,我想更新此表单上的 ListView 控件。
Job Class 的代码如下: 在 DoJob 函数中,我想在另一个 windows 窗体上更新 listview 控件中的一些状态
class ConnectToDatabase : Job
{
/// <summary>
/// Counter used to count the number of times this job has been
/// executed.
/// </summary>
private int counter = 0;
public ConnectToDatabase()
{
}
/// <summary>
/// Get the Job Name, which reflects the class name.
/// </summary>
/// <returns>The class Name.</returns>
public override string GetName()
{
return GetType().Name;
}
/// <summary>
/// Execute the Job itself. Just print a message.
/// </summary>
public override void DoJob()
{
Console.WriteLine(string.Format("This is the execution number \"{0}\" of the Job \"{1}\".", counter.ToString(), GetName()));
counter++;
}
/// <summary>
/// Determines this job is repeatable.
/// </summary>
/// <returns>Returns true because this job is repeatable.</returns>
public override bool IsRepeatable()
{
return true;
}
/// <summary>
/// Determines that this job is to be executed again after
/// 1 sec.
/// </summary>
/// <returns>1 sec, which is the interval this job is to be
/// executed repeatadly.</returns>
public override int GetRepetitionIntervalTime()
{
return 10000;
}
}
目前,我通过在表单的设计器类中使 listview 控件静态并从类中访问它来解决这个问题,但这种方法不是一个好的做法,因为设计器类是 IDE 的属性。实现此功能的最佳实践是什么
解决方案
Ok I found one more solution to my problem: Following code I've placed in the DoJob() function of the class and used Application.OpenForms["FormName"] to access the current instance of the form and then called its public function to set the listview control in the form
public void DoJob()
{
FormWorkFlow frm = (FormWorkFlow)Application.OpenForms["FormWorkFlow"];
if (frm.InvokeRequired)
{
frm.BeginInvoke(new Action(() =>
{
//This is public function in form that sets the listview control text
frm.SetListViewEventItems("This call is from the class", "it works");
}));
}
else
{
}
}
推荐阅读
- reactjs - React Native - 使用 Redux 将项目添加到 FlatList
- drupal - RuntimeException:NumberFormatter 需要 bcmath 扩展
- ios - 使用 TestFairy.begin() 时在 Xcode 9 中使用未解决的标识符“TestFairy”错误
- tomcat - 使用 dbcp2 和 ojdbc6 Oracle 驱动程序与 Tomcat 8 的连接泄漏
- entity-framework - 实体框架 - 主菜的最后一个 ID
- java - 字母顺序不适用于自定义 ListView
- python - 使 python 模块集合可安装
- docker - 如何解决 /dev/mapper/docker 满了?
- java - 如何在 spring redis executepiplelined as Map 中获取 hgetall 结果
- mysql - 将列值与另一个没有公共列的表匹配