为什么在这段代码中使用 Action?
你好 我看到以下代码:
void UpdateMessage (string message)
{
Action action = () => txtMessage.Text = message;
this.Invoke (action);
}
为什么使用 Action 然后在此处调用操作?为什么不直接使用 txtMessage.Text = message 来替换函数体中的代码?
更新
代码的完整版本,在评论中呈现,在下面复制,并带有语法突出显示、缩进等。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(Work).Start();
}
void Work()
{
Thread.Sleep(5000);
UpdateMessage("My Garden");
}
void UpdateMessage(string message) {
Action action = () => textBox1.Text = message;
this.Invoke(action);
}
}
Hi
I see following code:
void UpdateMessage (string message)
{
Action action = () => txtMessage.Text = message;
this.Invoke (action);
}
Why using Action and then invoke action here? Why not just using txtMessage.Text = message
to replace the code in function body?
Update
A fuller version of the code, presented in a comment, reproduced below with syntax highlighting, indentation etc.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(Work).Start();
}
void Work()
{
Thread.Sleep(5000);
UpdateMessage("My Garden");
}
void UpdateMessage(string message) {
Action action = () => textBox1.Text = message;
this.Invoke(action);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为此代码在与 UI 不同的线程上运行,并且必须使用
Invoke
编组到 UI 线程。Control.Invoke()
的文档状态:这都是必要的,因为底层 Windows 框架要求对窗口句柄的操作由拥有窗口句柄的线程执行。
Because this code runs on a different thread from the UI and must be marshalled across to the UI thread with
Invoke
.The documentation for
Control.Invoke()
states:This is all necessary because the underlying Windows framework requires that operations on a window handle are performed by the thread that owns the window handle.
如果从另一个线程调用 UpdateMessage,则需要调用主线程才能与 GUI 元素交互
如果仅使用
txtMessage.Text = message
,您将得到CrossThreadOperationException
If UpdateMessage is called from another thread you need to Invoke into main thread in order to interact with GUI elements
If you use just
txtMessage.Text = message
you will getCrossThreadOperationException
您应该在 UI 线程中使用控件的属性,否则您将收到异常。
Control.Invoke() 将通过向窗口消息循环发送窗口消息来执行您的委托。
但是您可以优化代码以防止不需要时不必要的线程同步:
You should work with a control's properties in the UI thread, otherwise you will receive exception.
Control.Invoke() will execute your delegate by sending windows message to the window message loop.
But you can optimize code to prevent unnecessary thread syncronization when it don't required: