相关疑难解决方法(0)

如何从其他线程更新GUI?

Label从另一个线程更新a的最简单方法是什么?

我有一Formthread1,并从我开始另一个线程(thread2).虽然thread2在处理一些文件,我想更新LabelForm用的当前状态thread2的工作.

我怎样才能做到这一点?

.net c# user-interface multithreading winforms

1331
推荐指数
41
解决办法
63万
查看次数

从另一个线程写入TextBox?

我无法弄清楚如何使C#Windows窗体应用程序从一个线程写入文本框.例如,在Program.cs中,我们有标准的main()来绘制表单:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}
Run Code Online (Sandbox Code Playgroud)

然后我们在Form1.cs中:

public Form1()
{
    InitializeComponent();

    new Thread(SampleFunction).Start();
}

public static void SampleFunction()
{
    while(true)
        WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. ";
}
Run Code Online (Sandbox Code Playgroud)

我完全错了吗?

UPDATE

以下是bendewey提供的工作代码示例:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        new Thread(SampleFunction).Start();
    }

    public void AppendTextBox(string value)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
            return;
        }
        textBox1.Text += value;
    }

    void SampleFunction()
    {
        // Gets executed on a seperate thread and 
        // doesn't block the …
Run Code Online (Sandbox Code Playgroud)

c# multithreading winforms

61
推荐指数
5
解决办法
14万
查看次数

如何从另一个线程更新GUI上的文本框

我是C#的新手,我正在尝试创建一个简单的客户端服务器聊天应用程序.

我在我的客户端窗体上有RichTextBox,我试图从另一个类的服务器更新该控件.当我尝试这样做时,我得到错误:"跨线程操作无效:控制textBox1从其创建的线程以外的线程访问".

这里是我的Windows窗体的代码:

private Topic topic;  
public RichTextBox textbox1;  
bool check = topic.addUser(textBoxNickname.Text, ref textbox1, ref listitems);
Run Code Online (Sandbox Code Playgroud)

主题类:

public class Topic : MarshalByRefObject  
{  
    //Some code
 public  bool addUser(string user, ref RichTextBox textBox1, ref List<string> listBox1)  
 {  
     //here i am trying to update that control and where i get that exception  
     textBox1.Text += "Connected to server... \n";  
}
Run Code Online (Sandbox Code Playgroud)

那怎么办呢?如何从另一个线程更新文本框控件?


我正在尝试使用.net远程处理来创建一些基本的聊天客户端/服务器应用程序.我想将Windows窗体客户端应用程序和控制台服务器应用程序作为单独的.exe文件.这里我试图从客户端调用服务器函数AddUser,我想要AddUser函数更新我的GUI.我已经修改了代码,因为你建议使用Jon,但是现在代替了跨线程异常,我得到了这个异常... "SerializationException:Assembly中的类型主题没有被标记为可序列化".

生病了我的整个代码,尽量保持简单.
任何建议都是受欢迎的.非常感谢.

服务器:

  namespace Test
{
    [Serializable]
    public class Topic : MarshalByRefObject
    {
        public bool AddUser(string user, …
Run Code Online (Sandbox Code Playgroud)

c# user-interface multithreading winforms

10
推荐指数
2
解决办法
7万
查看次数

标签 统计

c# ×3

multithreading ×3

winforms ×3

user-interface ×2

.net ×1