为什么在事件中,例如label1.Text应该等待结束事件以更新UI [英] why in the a event,For example label1.Text should wait for to ended the event to update UI

查看:85
本文介绍了为什么在事件中,例如label1.Text应该等待结束事件以更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能,请确定我的代码中的sendMesssage,postmessage,messaege pomp,message队列.为什么"label1.Text =" Csharp;必须等待才能结束.


if possible,Determined what sendMesssage,postmessage,messaege pomp,message queue in the my code .too why "label1.Text = "Csharp"; must be wait to envent to be ended.


public partial class Form1 : Form
  {
      public Form1()
      {
          InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {

          y();
          label1.Text = "Csharp";
          ThreadStart p=new ThreadStart(x);
          Thread g=new Thread(p);
          g.Start();
          y();

      }



      void y()
      {
          label2.Text = "mehdi";

      }

      void x()
      {
          label2.Text = "mehdi";
          Thread.Sleep(100);

      }
  }

推荐答案

我多次向您提及:停止在用户界面中间创建线程.这样,您可以产生任意数量的线程,每次单击一次.为什么?

从一开始就创建一个永久线程,并将任务提供给它.您只需要一个就可以了,对.例如,使用EventWaitHandle保持空闲线程,或使用阻塞队列.我多次推荐它,请参见:线程的简单阻塞队列通信和线程间调用 [.您需要调用它.呼叫中对y()的呼叫有效.

—SA
I mentioned to you many times: stop creating threads in the middle of your UI. This way you can spawn any number of threads, one per click. Why?

Create a permanent thread from the very beginning and feed tasks to it. You don''t need more then one, right. Hold idle thread with EventWaitHandle, for example, or use blocking queue. I recommended it many times, see this: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^]. Alternatively, take a thread from the thread poll, but again, don''t do it on every click.

Now button1_Click violates all possible Microsoft naming conventions. Don''t tell me it generated by Microsoft''s designer. Yes, but you''re not a robot to repeat it! Use anonymous delegate, grow up.

This is all a foreword, now a word:

You''re call x() in no-UI thread. It means you should not use UI operation label2.Text = "mehdi";. You need to Invoke it. A call to y() in your call is valid.

—SA


这篇关于为什么在事件中,例如label1.Text应该等待结束事件以更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆