Control.Invoke
The delegate can be an instance of EventHandler, in which case the sender parameter will contain this control, and the event parameter will contain EventArgs.Empty. The delegate can also be an instance of MethodInvoker, or any other delegate that takes a void parameter list. A call to an EventHandler or MethodInvoker delegate will be faster than a call to another type of delegate.
写法1
Control.BeginInvoke(new Action(DoSomething), null);
private void DoSomething()
{
MessageBox.Show("What a great post");
}OR
Control.BeginInvoke(new Action(() => MessageBox.Show("What a great post")));
写法2
Control.BeginInvoke((MethodInvoker) delegate {
MessageBox.Show("What a great post");
});
写法3
public static class FormsExt
{
public static void InvokeOnMainThread(this System.Windows.Forms.Control control, Action act)
{
control.Invoke(new MethodInvoker(act), null);
}
}
then
rtbOutput.InvokeOnMainThread(() =>
{
// Code to run on main thread here
rtbOutput.AppendText(fields[0].TrimStart().TrimEnd().ToString() + " Profile not removed. Check Logs.\n"); }));
});
写法4
样例:显示时间
public Form1() { // Create a timer that will call the ShowTime method every second. var timer = new System.Threading.Timer(ShowTime, null, 0, 1000); } private void ShowTime(object x) { // Don‘t do anything if the form‘s handle hasn‘t been created // or the form has been disposed. if (!this.IsHandleCreated && !this.IsDisposed) return; // Invoke an anonymous method on the thread of the form. this.Invoke((MethodInvoker) delegate { // Show the current time in the form‘s title bar. this.Text = DateTime.Now.ToLongTimeString(); }); }
时间: 2024-10-24 22:47:19