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

转自原文 线程间操作无效: 从不是创建控件的线程访问它.

 

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

namespace LoginIn
{
    public partial class Form1 : Form
    {
        delegate void MyDelegate(string name, string code);
        delegate void SetTipDelegate(string tip);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string name = txtName.Text;
            string code = txtCode.Text;
            //调用委托,用新线程校验用户名、密码
            MyDelegate myDelegate = new MyDelegate(CheckUser);
            myDelegate.BeginInvoke(name, code, null, null);
        }

        void CheckUser(string name, string code)
        {
            Thread.Sleep(2000);
            if (name == "1" && code == "1")
            {
                SetTip("成功");
            }
            else
            {
                SetTip("失败");
            }
        }

        void SetTip(string tip)
        {
            //是否调用Invoke方法
            if (lbTip.InvokeRequired)
            //if(!从创建控件“lbTip”的线程访问它)
            {
                //调用委托
                SetTipDelegate myDelegate = new SetTipDelegate(SetTip);
                Invoke(myDelegate, tip);
            }
            else
            {
                lbTip.Text = tip;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            button1.Text = DateTime.Now.ToString();
        }
    }
}

2015年8月3日 16:49:27,更新简写版

protected void button1_Click(object sender,EventArgs e)
        {
            string userName = txtName.Text;
            string userCode = txtCode.Text;
            
            Func<string ,string ,string> d1 = (name, code) =>           
                 (name == "1" && code == "1") ? "成功" : "失败";                            
                        
            d1.BeginInvoke(userName,userCode,ar=>
                           {
                               string result= d1.EndInvoke(ar);
                               Action<string> action1=data=>label1.Text=data;
                               Invoke(action1,result);
                           },
                           null);
        }

 

posted @ 2017-04-12 09:51  wenglabs  阅读(403)  评论(0编辑  收藏  举报