C# 代理和设置标签
因此,我使用这段代码的总体目标是从不同的线程(以安全的方式)设置标签的文本属性 呼叫代码:C# 代理和设置标签,c#,.net,multithreading,winforms,C#,.net,Multithreading,Winforms,因此,我使用这段代码的总体目标是从不同的线程(以安全的方式)设置标签的文本属性 呼叫代码: namespace csDinger3 { public class Program { // Some code that's not relevant public static void updateText(Int32 number) { setlblStarted x = new setlblStarted(
namespace csDinger3
{
public class Program
{
// Some code that's not relevant
public static void updateText(Int32 number)
{
setlblStarted x = new setlblStarted(ClientUI.setlblStarted_txt);
x(number.ToString());
}
}
}
据我所知(如果我错了,请纠正我),我需要创建一个新的setlblStarted\u txt
实例,将新实例指向方法setlblStarted\u txt
,但问题目前是ClientUI。setlblStarted\u txt
不是静态的,需要对象引用
我试过使用ClientUI c=newclientui()代码>,但这不起作用(因为它正在创建表单的新实例?)
我做错了什么?如果可能的话,您能帮助我理解为什么吗?在.Net 4.0中,您可以使用操作:
if (InvokeRequired)
{
Invoke(new Action<string>(updateText), "some text");
}
else
{
updateText("some text");
}
if(需要调用)
{
调用(新操作(updateText),“某些文本”);
}
其他的
{
updateText(“某些文本”);
}
另外,void updateText(字符串文本)
不需要是静态的。据我所知,您正在尝试使用MethodInvoker
委托来更新文本。我建议您更改此方法以简化代码:
namespace csDinger3
{
public class Program
{
static ClientUI aForm;
static void Main()
{
aForm = new ClientUI();
aForm.Show();
}
// Some code that's not relevant
public static void updateText(Int32 number)
{
aForm.setlblStarted_txt(number.ToString());
}
public partial class ClientUI : Form
{
public void setlblStarted_txt(string text)
{
if (lblStarted.InvokeRequired)
{
Invoke(new EventHandler(delegate
{
lblStarted.Text = text
}));
}
else
{
lblStarted.Text = text;
}
}
使用ThreadPool
或SynchronizationContext
或Dispatcher
(在WPF中)可以实现相同的行为。请参阅本教程以更好地理解:
您想要实现什么目标?在.NET 4.0中,大多数时候不需要声明委托。为什么要将此代码放在程序
类中?是它启动了这个应用程序。你应该把它放在WinForms类的代码后面。@Cameron我用它作为中心类,但我想我可以改变它easy@harismranbupdateText
位于不同的线程上,我需要调用方法setlblearn\u txt
。我是否将updateText
替换为setlblEarned\u txt
?
namespace csDinger3
{
public class Program
{
static ClientUI aForm;
static void Main()
{
aForm = new ClientUI();
aForm.Show();
}
// Some code that's not relevant
public static void updateText(Int32 number)
{
aForm.setlblStarted_txt(number.ToString());
}
public partial class ClientUI : Form
{
public void setlblStarted_txt(string text)
{
if (lblStarted.InvokeRequired)
{
Invoke(new EventHandler(delegate
{
lblStarted.Text = text
}));
}
else
{
lblStarted.Text = text;
}
}