C# 如何在c中从另一个非UI线程更新文本标签#
我有一个主线程,它为我的表单启动一个线程。我想从主线程更新label1文本。我已经创建了我的委托和更新它的方法,但我不知道如何访问表单线程和修改label1文本 这里是我的主要代码:C# 如何在c中从另一个非UI线程更新文本标签#,c#,.net,multithreading,C#,.net,Multithreading,我有一个主线程,它为我的表单启动一个线程。我想从主线程更新label1文本。我已经创建了我的委托和更新它的方法,但我不知道如何访问表单线程和修改label1文本 这里是我的主要代码: public class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Mai
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Thread l'affichage de la form
Program SecondThread = new Program();
Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));
th.Start();
//Update the label1 text
}
public void ThreadForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
如何访问表单线程和修改label1文本?我正在使用C#和.Net 4.5。您需要在第二个线程上访问表单对象,因此需要在程序类中公开它。然后,在main中,您应该能够通过暴露属性设置它
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Thread l'affichage de la form
Program SecondThread = new Program();
Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));
th.Start();
//Update the label1 text
while (SecondThread.TheForm == null)
{
Thread.Sleep(1);
}
SecondThread.TheForm.SetTextLabel("foo");
}
internal Form1 TheForm {get; private set; }
public void ThreadForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form1 = new Form1();
Application.Run(form1);
TheForm = form1;
}
}
公共类程序
{
///
///应用程序的主要入口点。
///
[状态线程]
静态void Main()
{
//螺纹l'affichage de la form
Program SecondThread=新程序();
Thread th=新线程(新线程开始(SecondThread.ThreadForm));
th.Start();
//更新label1文本
while(SecondThread.TheForm==null)
{
睡眠(1);
}
SecondThread.TheForm.SetTextLabel(“foo”);
}
内部Form1格式{get;private set;}
public-void-ThreadForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form1=新form1();
应用程序运行(form1);
形式=形式1;
}
}
我已将该行置于form=form1;在行应用程序之前运行(form1);它正在发挥作用。
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Thread l'affichage de la form
Program SecondThread = new Program();
Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));
th.Start();
//Update the label1 text
while (SecondThread.TheForm == null)
{
Thread.Sleep(1);
}
SecondThread.TheForm.SetTextLabel("foo");
}
internal Form1 TheForm {get; private set; }
public void ThreadForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form1 = new Form1();
Application.Run(form1);
TheForm = form1;
}
}