如何从现有线程plz帮助中调用函数 [英] how to call a function from a existing thread plz help

查看:99
本文介绍了如何从现有线程plz帮助中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个函数,但它给了我错误:
跨线程操作无效:从创建该线程的线程之外的线程访问控件"textBox1".
请帮助

hi i am calling a function but it is giving me error:
Cross-thread operation not valid: Control ''textBox1'' accessed from a thread other than the thread it was created on.
plz help

private void button1_Click(object sender, System.EventArgs e)
        {
            _t = new Thread(new ThreadStart(DoSomething));
            _t.Start();
        }
private Thread _t;
        private void DoSomething()
        {
            try
            {
                while(true)
                {
                   write(str);
                }
            }
            catch (ThreadAbortException ex)
            {
                MessageBox.Show("Loop break");
                return;
            }
        }
 public void WriteText(string str)
{
/*do something*/
}

 private void button2_Click(object sender, System.EventArgs e)
  {
            _t.Abort();
  }

推荐答案



您可以尝试以下代码:
Hi,

you can try this code:
private delegate void WriteTextCallback(string str);
public void WriteText(string str)
{
   if (this.InvokeRequired)
   {
      BeginInvoke(new WriteTextCallback(WriteText), new object[] { str });
      return;
   }
   TextBox1.Text = "Hallo";
}


UI控件只能从在其上创建的线程(UI线程)进行访问.如果尝试从其他线程执行此操作,则会出现错误.
您需要调用控件.这是执行此操作的通用方法:
UI controls can only be accessed from the thread they are created on (the UI thread). If you try to do so from a different thread, you get the error.
You need to Invoke the control. Here is a generic way to do it:
private void AddNewTab(string tabName)
    {
    if (InvokeRequired)
        {
        Invoke(new MethodInvoker(delegate { AddNewTab(tabName); }));
        }
    else
        {
        TabPage tp = new TabPage(tabName);
        myTabControl.TabPages.Add(tp);
        }
    }


这篇关于如何从现有线程plz帮助中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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