,我已經做了這樣的事情之前是使用計時器的方式。每當TrackBar的值發生變化時,重置定時器以使其在500ms內(或任何適合您的情況)觸發。如果用戶在定時器觸發前更改了該值,它將再次被重置,這意味着即使它多次更改,定時器也只會觸發一次。
這裏唯一需要注意的是計時器會觸發另一個線程,並且您將無法從該線程更新UI,因此您必須調用回UI線程才能進行更改那裏。不過,如果您可以將大部分昂貴的工作轉移到此後臺線程,則可以讓UI保持更長的響應時間。
下面是一些示例代碼,應該給你一些我的意思。
public partial class Form1 : Form
{
private int updateCount;
private System.Threading.Timer timer;
public Form1()
{
this.InitializeComponent();
this.timer = new System.Threading.Timer(this.UpdateValue);
}
private void UpdateValue(object state)
{
// Prevent the user from changing the value while we're doing
// our expensive operation
this.Invoke(new MethodInvoker(() => this.trackBar1.Enabled = false));
// Do the expensive updates - this is still on a background thread
this.updateCount++;
this.Invoke(new MethodInvoker(this.UpdateUI));
}
private void UpdateUI()
{
this.label1.Text = this.updateCount.ToString();
// Re-enable the track bar again
this.trackBar1.Enabled = true;
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
this.timer.Change(TimeSpan.FromMilliseconds(500), new TimeSpan(-1));
}
}
編輯:這是一個解決方案,它使用win窗體計時器來執行計時。這裏的區別在於,在計算運行時您將鎖定UI;這可能會或可能不會在你的情況下。
public partial class Form1 : Form
{
private int updateCount;
private Timer timer;
public Form1()
{
this.InitializeComponent();
this.timer = new Timer();
this.timer.Interval = 500;
this.timer.Tick += this.Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
this.timer.Stop();
this.updateCount++;
this.label1.Text = this.updateCount.ToString();
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
this.timer.Stop();
this.timer.Start();
}
}
mmmm,WPF? Silverlight的?的WinForms? (等) – 2011-04-19 14:30:04
它在WinForms – 2011-04-19 14:48:36
謝謝你,現在你會得到更好的答案:) – 2011-04-19 14:51:29