滥用线程你不担心吗?你应该使用 Timer。
解决方案 »
- webbrowser如何阻止网页关闭后再弹出窗口?
- 请问,这个关于listbox的代码哪里错了
- 用C#可以做工控机的程序么?
- 关于WebRequest
- 用数组方法连续输入五个姓名怎样用代码实现?
- MSMQ: 消息队列客户端数量的问题
- winform中怎样使datagrid的cell不能获得焦点?
- WPF中,TreeViewItem的'+'和'-'点击后无效果
- 已连接好的socket对象中,有没有创建时间的属性,或这个socket连接已持续多长时间了
- xp系统下如何安装vs.net
- 针对任何数值类型的排序算法
- new Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr)是否和Intptr参数共享数据内存?
public class MyForm : System.Windows.Forms.Form {
//UI 元素
private Label lblStatus;
private ProgressBar progressBar1; //Delegate
private delegate void MyProgressEventsHandler(
object sender, MyProgressEvents e);
private void UpdateUI(object sender, MyProgressEvents e) {
lblStatus.Text = e.Msg;
myProgressControl.Value = e.PercentDone;
} //ShowProgress 现在可以记录为可从任何线程调用的公共方法。
public void ShowProgress(string msg, int percentDone)
{
if(InvokeRequired)
{
System.EventArgs e = new MyProgressEvents(msg, percentDone);
object[] pList = { this, e }; BeginInvoke(new MyProgressEventsHandler(UpdateUI), pList);
}
else
{
UpdateUI(this, new MyProgressEvents(msg,
PercentDone));
}
} private void btnStart_Click(object sender, EventArgs e)
{
//启动线程
Thread t = new Thread(new ParameterizedThreadStart(RunsOnWorkerThread));
t.IsBackground = true;
t.Start(input);
} //线程执行函数
private void RunsOnWorkerThread()
{
int i = 0;
while(...) //loop
{
DoSomethingSlow();
ShowProgress("test",i);
++i;
}
}
}这个例子没有用匿名函数和lambda表达式,好理解些
{
Thread.Sleep(16000);
textBox1.BeginInvoke(new InvokeDelegate(InvokeMethod));
}
public void InvokeMethod()
{
textBox1.Text = "Executed the given delegate";
}
但是实际上滥用线程实在是没有必要。Timer是操作系统的中断控制的,是高效率的机制,触发事件之前只需要注册而不需要占用任何线程,不是你的线程可比的。