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#中的委托语法问题
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01