搜索关键字问题汇总

案例一

用C#写windows forms程序时,遇到在新建的线程里操作主线程的form元素会报一个异常,说不能在操作其他线程的form元素。

当时第一想到的方案是,这里是不是需要跨线程通信,于是搜索C# 线程通信怎么做,以及多线程如何处理等等。

 

搜索关键字问题汇总_第1张图片

看了一圈觉得有点复杂,而且一遍文章被转来转去。

后面我回到问题本身,搜索多线程与form的关系,找到微软自己的文档。

搜索关键字问题汇总_第2张图片

 

这篇文章详细说明了,在其他线程里调用form元素会导致一些不可预料的事情,所以系统提供了两个方式来解决这个问题,其中一个是提供一个安全调用的方式,每次操作form元素只要判断一下元素和自己是否在同一个线程,如果不是,就采用安全调用方式即可。完成这个操作,都不需要设计到线程通信的层面。

具体代码如下:

在windows form元素上采用线程安全的调用

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

public class InvokeThreadSafeForm : Form
{
    private delegate void SafeCallDelegate(string text);
    private Button button1;
    private TextBox textBox1;
    private Thread thread2 = null;

    [STAThread]
    static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new InvokeThreadSafeForm());
    }
    public InvokeThreadSafeForm()
    {
        button1 = new Button
        {
            Location = new Point(15, 55),
            Size = new Size(240, 20),
            Text = "Set text safely"
        };
        button1.Click += new EventHandler(Button1_Click);
        textBox1 = new TextBox
        {
            Location = new Point(15, 15),
            Size = new Size(240, 20)
        };
        Controls.Add(button1);
        Controls.Add(textBox1);
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        thread2 = new Thread(new ThreadStart(SetText));
        thread2.Start();
        Thread.Sleep(1000);
    }

    private void WriteTextSafe(string text)
    {
        if (textBox1.InvokeRequired)
        {
            var d = new SafeCallDelegate(WriteTextSafe);
            textBox1.Invoke(d, new object[] { text });
        }
        else
        {
            textBox1.Text = text;
        }
    }

    private void SetText()
    {
        WriteTextSafe("This text was set safely.");
    }
}

总结:

虽然自己想当然的扩展搜索关键字能搜到更多的东西,但是有时还是要贴近描述问题本身去搜索,可能会更快找到最终的答案。

你可能感兴趣的:(issue)