---
title: "线程访问winform界面控件的例子"
author: "pignut_wang"
date: "2008-10-07T22:24:03Z"
tags: []
categories: ["企业架构"]
slug: "winform"
draft: false
lastmod: "2008-10-07T22:24:03Z"
id: 250087
url: "https://pignut-wang.iteye.com/blog/250087"
---

本例子主要是针对解决异常:

线程间操作无效: 从不是创建控件“richTextBox1”的线程访问它

关键看红色的代码,详细的查MSDN.

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  
using System.Threading;

namespace WindowsFormsApplication1  
{  
    public delegate void MyInitDelegate(RichTextBox myRtb, string strTemp);

    public partial class Form1 : Form  
    {

        public Form1()  
        {  
            InitializeComponent();

        }

        private void Form1\_Load(object sender, EventArgs e)  
        {  
            Thread t = new Thread(new ThreadStart(this.output));  
            t.Start();  
        }

        private void output()  
        {  
            string message = "pppp";  
            this.richTextBox1.BeginInvoke(new MyInitDelegate(DelegateInitMethod), new object\[] { this.richTextBox1, message });  
        }

        public void DelegateInitMethod(RichTextBox myRtb, string strTemp)  
        {  
            myRtb.AppendText(System.Environment.NewLine + strTemp);  
        }

    }  
}