②通常可以把耗时的操作放到子线程里执行,然后再调用BeginInvoke/Invoke方法
③Control的BeginInvoke是相对于工作线程(工作线程是调用BeginInvoke方法的线程)是异步的。
工作线程不管是UI线程还是子线程,Invoke需要阻塞工作线程执行,而BeginInvoke不需要阻塞工作线程执行。
UI线程:
private void button76_Click(object sender, EventArgs e) {
Console.WriteLine("1"); this.Invoke(new Action(() => {
Thread.Sleep(1000); Console.WriteLine("2"); })); Console.WriteLine("3"); } private void button85_Click(object sender, EventArgs e) {
Console.WriteLine("4"); this.BeginInvoke(new Action(() => {
Thread.Sleep(1000); Console.WriteLine("5"); })); Console.WriteLine("6"); } }
子线程:
private void button76_Click(object sender, EventArgs e) {
Thread t = new Thread(()=> {
Console.WriteLine("1"); this.Invoke(new Action(() => {
Thread.Sleep(10000); Console.WriteLine("2"); })); Console.WriteLine("3"); }); t.Start(); } private void button85_Click(object sender, EventArgs e) {
Thread t = new Thread(() => {
Console.WriteLine("4"); this.BeginInvoke(new Action(() => {
Thread.Sleep(10000); Console.WriteLine("5"); })); Console.WriteLine("6"); }); t.Start(); } }

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/222416.html原文链接:https://javaforall.net
