首页 > 解决方案 > 从在 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 的属性。实现此功能的最佳实践是什么

标签: c#.netmultithreadingwinforms

解决方案


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

推荐阅读