跨线程操作UI控件.BeginInvoke(new action())
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void AppendMsgHandler(DataObject dataobject);
public struct DataObject
{
internal string Msg;
internal TextBox cText;
}
public void AppendMsg(DataObject dataObject)
{
if (textBox1.InvokeRequired)
{
textBox1.BeginInvoke(new Action<DataObject>(AppendMsg), dataObject);
}
else
{
dataObject.cText.Text += dataObject.Msg + "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
AppendMsgHandler theHandle = AppendMsg;
IAsyncResult IResult = theHandle.BeginInvoke(new DataObject() { Msg = DateTime.Now.ToString("O"), cText = textBox1 }, null, null);
if (IResult.IsCompleted)
{
MessageBox.Show("Done");
}
}
}
}