111,120
社区成员
发帖
与我相关
我的任务
分享do
{
sRet = WriteWalletInfo(ref CardBurseInfo, nCurCard, iWalletNum, dMonDeal, "11", out sErrText);
if (!sRet)
{
lb_Msg.Text = "写卡失败,请重试!";
}
}
while (!sRet);
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace TestWaitNotify {
public partial class Form1 : Form {
private Thread thread = null;
private bool running = false;
public Form1() {
InitializeComponent();
}
private void execute() {
running = true;
int i = 0;
while (running) {
Console.WriteLine("执行操作 " + ++i + " ……");
}
Console.WriteLine("完成 ……");
thread = null;
}
private void btnStart_Click(object sender, EventArgs e) {
if (thread == null) {
thread = new Thread(new ThreadStart(this.execute));
thread.Start();
}
}
private void btnStop_Click(object sender, EventArgs e) {
running = false;
}
}
}
[/quote]
重点是你既然在主线程死循环,然后又纠结在死循环的时候要响应按键事件,这是自相矛盾的。
斯国一
Sleep(0)[/quote]
sleep(0)有不妥吗?
According to MSDN's documentation for Sleep:
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution.
The important thing to realize is that yes, this gives other threads a chance to run, but if there are none ready to run, then your thread continues -- leaving the CPU usage at 100% since something will always be running. If your while loop is just spinning while waiting for some condition, you might want to consider using a synchronization primitive like an event to sleep until the condition is satisfied or sleep for a small amount of time to prevent maxing out the CPU.
Sleep(0)