C# 从运行在C中单独线程上的外部类更新Widnows表单控件(listview)#
我有一个带有ListView控件的Windows窗体。我有另一个类“job”,它被实例化,并在加载后在这个表单的一个单独线程上执行。 我想在类执行某些操作时更新此窗体上的ListView控件 Job类的代码如下:在DoJob函数中,我想更新另一个windows窗体上listview控件中的一些状态C# 从运行在C中单独线程上的外部类更新Widnows表单控件(listview)#,c#,.net,multithreading,winforms,C#,.net,Multithreading,Winforms,我有一个带有ListView控件的Windows窗体。我有另一个类“job”,它被实例化,并在加载后在这个表单的一个单独线程上执行。 我想在类执行某些操作时更新此窗体上的ListView控件 Job类的代码如下:在DoJob函数中,我想更新另一个windows窗体上listview控件中的一些状态 class ConnectToDatabase : Job { /// <summary> /// Counter used to count the number of
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;
}
}
class ConnectToDatabase:作业
{
///
///计数器,用于计算此作业已完成的次数
///执行。
///
专用整数计数器=0;
公共ConnectToDatabase()
{
}
///
///获取反映类名的作业名称。
///
///类名。
公共重写字符串GetName()
{
返回GetType().Name;
}
///
///执行作业本身。只需打印一条消息。
///
公共覆盖无效DoJob()
{
Console.WriteLine(string.Format(“这是作业\“{1}\”的执行编号\“{0}\”,counter.ToString(),GetName());
计数器++;
}
///
///确定此作业是可重复的。
///
///返回true,因为此作业是可重复的。
公共覆盖bool IsRepeatable()
{
返回true;
}
///
///确定此作业将在之后再次执行
///1秒。
///
///1秒,即此作业的间隔时间
///反复执行。
公共覆盖int GetRepetitionIntervalTime()
{
返回10000;
}
}
目前,我通过在窗体的设计器类中使listview控件保持静态并从类中访问它来解决此问题,但这种方法不是一种好的做法,因为设计器类是IDE的属性。实现此功能的最佳实践是什么?好的,我找到了解决问题的另一个方法:在类的DoJob()函数中放置以下代码,并使用Application.OpenForms[“FormName”]访问表单的当前实例,然后调用其公共函数在表单中设置listview控件
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
{
}
}
你能告诉我你遇到了什么问题吗?刚刚编辑了我的问题。目前,我通过在窗体的设计器类中使listview控件保持静态并从类中访问它来解决此问题,但这种方法不是一种好的做法,因为设计器类是IDE的属性。实现此功能的最佳实践是什么?如何在类/窗体之间传递数据?问题。要得到“最佳实践”的答案,最好的办法是发布当前的解决方案,如果您还没有代码,那么请询问。还有一件事。我首先加载Windows窗体,然后运行类的实例。我怎样才能在类中获得加载的表单实例它的可能副本对我有用。是的,最好使用加载的表单实例,而不是让Windows表单控制静态