110,533
社区成员
发帖
与我相关
我的任务
分享
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//这里加一个300秒的延迟避免频繁查询的问题
//但是有一个问题 this.label1.Text的上的文字延迟了
//this.textBox1.Text这个也延迟(这个不是我想要的)
// 在this.textBox1.Text 快速输入 123456 但是在this.textBox1.Text上有明显的延迟 这不是我们想要的
System.Threading.Thread.Sleep(300);
this.label1.Text = this.textBox1.Text;//这个地方将来要换成查询数据库的操作逻辑代码
// 应该this.label1.Text 整个显示是延迟的 this.textBox1.Text显示是同步的 需要用到线程的一部调用吗?怎么实现?
}
#region 事件延迟触发
public static delegate void DoWorkAsyncDelegate(SynchronizationContext context, SendOrPostCallback task, object state, int millisecond);
public static void DoWork(SendOrPostCallback task, object state, int millisecond)
{
new DoWorkAsyncDelegate(DoWorkAsync).BeginInvoke(DispatcherSynchronizationContext.Current, task, state, millisecond, null, null);
}
static void DoWorkAsync(SynchronizationContext context, SendOrPostCallback task, object state, int millisecond)
{
System.Threading.Thread.Sleep(millisecond);
context.Post(task, state);
}
#endregion
调用:
void textBox1Tolabel1(object state)
{
this.label1.Text = this.textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DoWork(textBox1Tolabel1,null,300);
}
public static void DoWork(SendOrPostCallback task, object state = null, int millisecond = 1000)
{
new Action<SynchronizationContext, SendOrPostCallback, object, int>(DoWorkAsync).BeginInvoke(SynchronizationContext.Current, task, state, millisecond, null, null);
}
static void DoWorkAsync(SynchronizationContext context, SendOrPostCallback task, object state, int millisecond)
{
System.Threading.Thread.Sleep(millisecond);//等待原有线程刷新完毕
context.Post(task, state);
}
调用:
void textBox1Tolabel1(object state)
{
this.label1.Text = this.textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DoWork(textBox1Tolabel1);
}
public delegate void DelayHanddler();
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
new System.Threading.Thread(new System.Threading.ThreadStart(myThread)).Start();
}
public void myThread()
{
DelayHanddler dh=new DelayHanddler(Delay);
this.BeginInvoke(dh);
}
private void Delay()
{
Thread.Sleep(300);
this.label1.Text = this.textBox1.Text;
}
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
timer.Interval = TimeSpan.FromMilliseconds(300);
timer.Tick += timer_Tick;
}
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
this.label1.Text = this.textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
timer.Start();
}