从ex.Form1.cs之外的其他类的thrad更新GUI [英] Update GUI from a thrad of different class other than ex.Form1.cs

查看:73
本文介绍了从ex.Form1.cs之外的其他类的thrad更新GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在创建一个基于Windows的应用程序,可以从服务器下载数据.
我正在使用在不同类上创建的后台线程来执行这些下载操作.并且我想在富文本框(即主线程)上连续显示下载状态.但是我无法做到这一点,所以请不要执行跨线程操作有效.
请帮助我解决此问题.

Hi,
I am creating an windows based application which download the data from server.
I am using the background thread which is created on different class to perform these download operation.And I want to continuously show the download status on rich textbox i.e on main thread.But i am unable to do this,get an Cross-thread operation not valid.
Please help me to resolve this problem.

推荐答案

要更新文本,请在Form1中使用公共或内部方法.检查InvokeRequired属性.如果为true,则调用this.Invoke在同一函数上.例如
For updating the text, use a public or internal method in Form1. Check the InvokeRequired property. If it is true, call this.Invoke on the same function. E.g.
public void UpdateText(string newText)
{
    if (InvokeRequired)
    {
        this.Invoke(new AFStringDelegate(UpdateText), newText);
        return;
    }
    textbox.Text = newText;
}


该委托在Microsoft的应用程序框架中可用.您也可以声明它:


The delegate is available in Microsoft''s Application Framework. You can also declare it:

public delegate void AFStringDelegate(string s);


现在,从后台线程调用UpdateText方法.


And now call the UpdateText method from your background thread.


您可以使用Background辅助程序,然后使用在主线程中处理的ProgressChanged事件.参见此示例:
You could use a Background worker and then use the ProgressChanged event which is handled in the main thread. See this sample:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   //Tasks executed in separate thread
   backgroundWorker1.WorkerReportsProgress = true;
   backgroundWorker1.ReportProgress(1);
   Thread.Sleep(500);
   backgroundWorker1.ReportProgress(2);
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   //event handler in main thread - update GUI here
}


这篇关于从ex.Form1.cs之外的其他类的thrad更新GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆