在fo​​r循环中线程睡眠 [英] Thread sleep in a for loop

查看:166
本文介绍了在fo​​r循环中线程睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你们的帮助,使用此方法:

I need your help for using this method:

for (int i =0; i<dt.count; i++)
{
    process...
    sleep(3000);
}

int sleeptime=0;
private void timer2_Tick(object sender, EventArgs e)
{
    for (int i = 0; i &#60; mylist.Items.Count;)
    {
        listBox1.Items.Add(mylist.Items[i].Name.ToString() + "starting...");
        sleeptime = int.Parse(mylist.Items[i++].TimeSpan.ToString()) - timer2.Interval;
        System.Threading.Thread.Sleep(sleeptime);
    }
    timer1.Start();
    timer2.Stop();
}

但我不喜欢看到我的瀑布数据流。

But I don't see my data flow like waterfall.

推荐答案

正在阻塞UI线程 - 没有更新通常会告诉直到你离开的事件处理程序。哈克的方法是使用 Application.DoEvents(),但这是懒惰和风险重入的尤其的,如果你暂停。

You are blocking the UI thread - no updates will usually show until you leave the event-handler. A hacky approach is to use Application.DoEvents(), but this is lazy and risks re-entrancy especially if you are pausing.

一个更好的方法是做一个后台线程的工作,并使用调用将数据推到UI(不从工人交谈的UI线程)。

A better approach is to do the work on a background thread, and use Invoke to push the data to the UI (don't talk to the UI from the worker thread).

或者只是在不同的刻度添加单个项目?

Or just add individual items in separate ticks?

下面是使用的例子的BackgroundWorker 的工作,使用 ReportProgress 来推动项目到UI:

Here's an example using BackgroundWorker for the work, using ReportProgress to push items onto the UI:

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
static class Program
{
    static void Main()
    {
        // setup some form state
        Form form = new Form();
        ListView list = new ListView();
        list.View = View.List;
        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        form.Controls.Add(list);
        list.Dock = DockStyle.Fill;
        // start the worker when the form loads
        form.Load += delegate {
            worker.RunWorkerAsync();
        };
        worker.DoWork += delegate
        {
            // this code happens on a background thread, so doesn't
            // block the UI while running - but shouldn't talk
            // directly to any controls
            for(int i = 0 ; i < 500 ; i++) {
                worker.ReportProgress(0, "Item " + i);
                Thread.Sleep(150);
            }
        };
        worker.ProgressChanged += delegate(object sender,
           ProgressChangedEventArgs args)
        {
            // this is invoked on the UI thread when we
            // call "ReportProgress" - allowing us to talk
            // to controls; we've passed the new info in
            // args.UserState
            list.Items.Add((string)args.UserState);
        };
        Application.Run(form);
    }
}

这篇关于在fo​​r循环中线程睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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