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# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01