• 线程间操作无效: 从不是创建控件“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.

  • 相关阅读:
    WinJS Clipboard
    -ms-grid -ms-grid-rows -ms-grid-row -ms-grid-columns -ms-grid-column
    严格模式 (JavaScript)
    windows rt 扫描二维码
    winmd文件和dll文件的区别
    Windows store 验证你的 URL http:// 和 https:// ms-appx:/// ms-appdata:///local
    使用C#在Windows应用商店程序中获取CPU信息
    python面向对象基础-01
    python红蓝英雄大乱斗(面向对象实现)
    python购物车升级版
  • 原文地址:https://www.cnblogs.com/cnbwang/p/1923678.html
Copyright © 2020-2023  润新知