zoukankan      html  css  js  c++  java
  • 线程间操作无效: 从不是创建控件“textBox1”的线程访问它。

    问题产生和现象:

    垮线程调用控件属性,现象如下:

    解决方法:

    方法1

    Control.CheckForIllegalCrossThreadCalls = false;

    方法2

    private void button1_Click(object sender, EventArgs e)
    {
    Thread.CurrentThread.Name
    = "Form Thread";
    Thread td
    = new Thread(new ThreadStart(SetControlText));
    td.Name
    = "Customer Thread";
    td.Start();
    }
    private void SetControlText()
    {
    if (this.InvokeRequired)
    {
    this.Invoke(new Action(SetControlText));
    }
    else
    {
    this.textBox1.Text = DateTime.Now.ToString();
    }
    }

    通用起见,可以考虑这样做:

    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    Thread.CurrentThread.Name
    = "Form Thread";
    Thread td
    = new Thread(new ThreadStart(SetControlText));
    td.Name
    = "Customer Thread";
    td.Start();
    }
    private void SetControlText()
    {
    this.InvokeIfNeeded(delegate(string str) { this.textBox1.Text = str; }, DateTime.Now.ToString("yyMMdd"));
    // or
    //this.InvokeIfNeeded((str)=> this.textBox1.Text = str,DateTime.Now.ToString("yyMMdd"));
    }
    }
    public static class ControlExtensions
    {
    public static void InvokeIfNeeded<T>(this Control ctl, Action<T> act, T args)
    {
    if (ctl.InvokeRequired)
    {
    ctl.Invoke(act, args);
    }
    else
    {
    act(args);
    }
    }
    }

    备注:

    Control.InvokeRequired Property

    Usage

    Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.

    Property Value

    true if the control's Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false.

  • 相关阅读:
    JQuery:JQuery语法、选择器、事件处理
    循序渐进DB2(第2版)——DBA系统管理、运维与应用案例
    高级进阶DB2(第2版)——内部结构、高级管理与问题诊断
    DB2数据库性能调整和优化(第2版)
    金融工程中的蒙特卡罗方法
    代数学教程
    拓扑线性空间与算子谱理论
    李代数(第2版)
    编程的修炼(中英双语)
    iOS应用开发详解
  • 原文地址:https://www.cnblogs.com/cnbwang/p/1923678.html
Copyright © 2011-2022 走看看