做一个网络应用程序一个form中 要实时判断显示远程数据库的一个“总数”字段我是用timer控件每隔2秒中探测一次private void timer2_Tick(object sender, System.EventArgs e)
{ this.label9.Text ="这是远程结果"
}但是这样运得程序在慢了,请问怎样用多线程实现后台每隔2秒探测呀
请写写代码
{ this.label9.Text ="这是远程结果"
}但是这样运得程序在慢了,请问怎样用多线程实现后台每隔2秒探测呀
请写写代码
private void set()
{
while (true)
{
//处理事件
thread.sleep(2000);
}
}Thread sth ;form_load()
{
sth = new Thread(new threadstart(set));
sth.start();
}大体上是这样,没有开发环境,写不出来。
1,自己手动建立线程。
2.用.net内置的异步调用实现多线程。
Timer支持异步调用,所以可以用委托实现多线程。
大致这样。msdn提供了一个例子,代码如下。
楼主看看,稍改一下就可以了。using System;
using System.Threading;
class TimerExample
{
static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10); // Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(statusChecker.CheckStatus); // Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer =
new Timer(timerDelegate, autoEvent, 1000, 250); // When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n"); // When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}class StatusChecker
{
int invokeCount, maxCount; public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
} // This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString()); if (invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}
public Timer stateTimer;
static void Main()
{
TimerCallback timerDelegate =new TimerCallback(CheckStatus);//建委托
stateTimer =new Timer(timerDelegate, null, 1000, 250);//要保证timer的存活期。
}
public static void CheckStatus(Object stateInfo)
{
this.label9.Text ="这是远程结果";
}