作者toki (いまがその时だ)
看板C_Sharp
标题Re: [问题] delegate.BeginInvoke跟control.invoke …
时间Thu Nov 22 10:50:33 2007
※ 引述《reptile0426 ( )》之铭言:
: 首先先感谢toki大的解说,他讲的是control.BeginInvoke的观念
: 後来我自己又看了一下两者的差别
我也看错 title XD 一看到 BeginInvoke 就想到 Control.BeginInvoke
基本上分别是这样的
Return Work Thread
Control.Invoke 完成工作 强制於 UI Thread
Control.BeginInvoke 立即 强制於 UI Thread
[delegate].Invoke 完成工作 Call Invoke 的 Thread
[delegate].BeginInvoke 立即 新的背景 Thread
你可以开一个新的 Windows Application 专案,然後新增
1、Button = button1
2、TextBox = textBox1 (请设 multiline)
然後把 button1 的 OnClick 连到下面 source code 里的 button1_Click
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public delegate void testDelegate(string text);
public Form1()
{
InitializeComponent();
}
private void UpdateTextBox(string text)
{
textBox1.Text += string.Format("{0}{1}", text, Environment.NewLine);
}
private void button1_Click(object sender, EventArgs e)
{
testDelegate t = new testDelegate(UpdateTextBox);
this.Invoke(t, "Control.Invoke");
this.BeginInvoke(t, "Control.BeginInvoke");
t.Invoke("[delegate].Invoke");
// 建议先 comment 掉下面这行跑一次,再拿掉 comment 跑一次
// 下面这行就是所谓的 [delegate].BeginInvoke
// 但是当你 call 了之後,在 UpdateTextBox 里会出现 exception
// 因为它使用新的背景 thread 来跑这个工作
// 但是 Form 不允许由别的 thread 来 access Form 上的任何 control
// t.BeginInvoke("[delegate].BeginInvoke", null, null);
}
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 60.248.161.34
1F:推 reptile0426:十分(!)清楚明辽~谢谢了toki大 11/22 12:38