Problem with delegate Syntax in C#(C#中的委托语法问题)
问题描述
我构建了一个测试箱来了解有关 Windows 窗体应用程序中的线程的知识.Silverlight 和 Java 正在提供 Dispatcher,这在更新时确实很有帮助GUI 元素.
I built a Testbox to learn something about threading in windows form applications. Silverlight and Java are providing the Dispatcher, which really helps when updating GUI Elements.
代码示例:声明类委托
public delegate void d_SingleString(string newText);
创建线程
_thread_active = true;
Thread myThread = new Thread(delegate() { BackGroundThread(); });
myThread.Start();
线程函数
private void BackGroundThread()
{
while (_thread_active)
{
MyCounter++;
UpdateTestBox(MyCounter.ToString());
Thread.Sleep(1000);
}
}
委派文本框更新
public void UpdateTestBox(string newText)
{
if (InvokeRequired)
{
BeginInvoke(new d_SingleString(UpdateTestBox), new object[] { newText });
return;
}
tb_output.Text = newText;
}
有没有办法在 BeginInvoke 方法中声明延迟声明?!
Is there a way to declare the Declaration of the Delate IN the BeginInvoke Method?!
类似
BeginInvoke(*DELEGATE DECLARATION HERE*, new object[] { newText });
非常感谢,雷特
推荐答案
在很多这样的情况下,最简单的方法是使用捕获的变量"在线程之间传递状态;这意味着您可以保持逻辑本地化:
In many cases like this, the simplest approach is to use a "captured variable" to pass state between the threads; this means you can keep the logic localised:
public void UpdateTestBox(string newText)
{
BeginInvoke((MethodInvoker) delegate {
tb_output.Text = newText;
});
}
如果我们期望在工作线程上调用它(很少点检查InvokeRequired
),上述内容特别有用 - 请注意,这对于任何一个 UI 都是安全的或工作线程,并允许我们在线程之间传递尽可能多或尽可能少的状态.
The above is particularly useful if we expect it to be called on the worker thread (so little point checking InvokeRequired
) - note that this is safe from either the UI or worker thread, and allows us to pass as much or as little state between the threads.
这篇关于C#中的委托语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#中的委托语法问题


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01