Pen*_*uen 1 .net c# multithreading winforms
我需要你的帮助才能使用这个方法:
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 < 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();
}
Run Code Online (Sandbox Code Playgroud)
但我没有看到我的数据流如瀑布.
Mar*_*ell 13
您正在阻止UI线程 - 在您离开事件处理程序之前,通常不会显示任何更新.一个hacky方法是使用Application.DoEvents()
,但这是懒惰的,并且冒着重新入侵的风险,特别是如果你正在暂停.
更好的方法是在后台线程上完成工作,并使用Invoke
将数据推送到UI(不要从工作线程与UI通信).
或者只是在单独的刻度中添加单个项目?
这是一个BackgroundWorker
用于工作的示例,ReportProgress
用于将项目推送到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);
}
}
Run Code Online (Sandbox Code Playgroud)