如何在界面和睡眠背景中使线程活跃 [英] How to make thread alive in interface and sleep background

查看:90
本文介绍了如何在界面和睡眠背景中使线程活跃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图每隔5秒在列表中添加新项目,但Iam在1秒内获得整个输出。



I am trying to add new item in list every 5 seconds but Iam getting whole output within 1 sec.

private void button_PrintNumber_Click(object sender, EventArgs e)
     {


         for (int i = 1; i <= 10; i++)
         {
           Thread backGroundThread = new Thread(DoTime); //here it does not wait for 5 sec?
             backGroundThread.Start();
             listBox1.Items.Add(i);

         }
     }
     private void DoTime()
     {

         Thread.Sleep(1000);
     }





我尝试过:





What I have tried:

private void button_PrintNumber_Click(object sender, EventArgs e)
     {


         for (int i = 1; i <= 10; i++)
         {
           Thread backGroundThread = new Thread(DoTime); //here it does not wait for 5 sec?
             backGroundThread.Start();
             listBox1.Items.Add(i);

         }
     }
     private void DoTime()
     {

         Thread.Sleep(1000);
     }

推荐答案

首先,给予Thread.Sleep的值以毫秒为单位,而不是5毫秒的部分:另一个线程休眠1秒。

但是你在另一个线程中执行此操作,因此主线程不受此影响。你必须在不同的线程中执行该循环 - 然后你必须在ListBox上调用Invoke,因为不能从不同的线程访问UI元素。

尝试类似:

First of all, the value given to Thread.Sleep is in Milliseconds, not in portions of 5 Milliseconds: the other thread sleeps 1 second.
But you do that in a different thread, and consequently the main thread is not affected by that. You have to do that loop in the different thread - and then you have to call Invoke on the ListBox because UI elements must not be accessed from a different thread.
Try something like:
private void button_PrintNumber_Click(object sender, EventArgs e)
{
    Thread backGroundThread = new Thread(DoTime); 
    backGroundThread.Start();
}

private void DoTime()
{
     for (int i = 1; i <= 10; i++)
     {
          Thread.Sleep(5000);
          listBox1.Invoke(new Action(() => listBox1.Items.Add(i)));
     }
}


这篇关于如何在界面和睡眠背景中使线程活跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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