我有微芯片mcp2200设备。设备上附加了树形按钮(作为数字输入)。我用它作为反馈机。
我将它附加到 Windows Server 2003 x64。然后我在我的 C# 应用程序中使用了 microchips mcp2200 驱动程序和托管 SimpleIO DLL。
在 C# 中,我使用频率为 500 毫秒的时间来检查按钮是否被按下。一两个小时后,服务器的 CPU 使用率一直很高。如果我杀死 C# 程序,一切都好。我怎样才能爱cpu使用?还是我的代码有问题?
一些代码:
void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.ToString("HH") == _turnOffApp) Environment.Exit(0); //after working hours, turn off app. Task scheduler will start it at 8 AM
if (btn_down == 99)
{ //if button is UP
bool connStatus = SimpleIOClass.IsConnected();
if (connStatus)
{
lblConnStatus.Text = "Connected";
unsafe
{
uint rez1 = 2;
uint* rez = &rez1;
for (uint i = 0; i < 8; i++)
{
if (i == 5 || i == 7) continue; //unused pins
rez1 = 2;
if (SimpleIOClass.ReadPin(i, rez))
{
string rez11 = rez1.ToString();
this.Controls["label" + i.ToString()].Text = rez1.ToString();
if (rez1.ToString() == "0") // 0 = button down, 1 = button up
{
RegisterButton(i);
i = 8;
continue;
}
}
else
{
try { this.Controls["label" + i.ToString()].Text = "ReadPinErr"; }
catch { }
}
}
}
}
else
{
lblConnStatus.Text = "NOT Connected";
}
}//end btn_down == 99
}
void RegisterButton(uint poga)
{
btn_down = poga;
device = Device(poga);
CheckUserInput();
}
void SendBtnToServer(string btn)
{
try
{
string uri = @"http://web-server.lan/pogas.php?device="+ device+ "&p=" + btn;
WebClient clietn = new WebClient();
clietn.Headers.Add("Cache-Control", "no-cache");
clietn.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
clietn.DownloadString(uri);
clietn.Dispose();
}
catch (Exception ex) { try { File.AppendAllText(logFails, DateTime.Now.ToString() + " " + ex.ToString() + "\n\r"); } catch { } }
}
void CheckUserInput()
{
Thread.Sleep(2000); //wait 2 sec until user releases button
bool connStatus = SimpleIOClass.IsConnected();
if (connStatus)
{
lblConnStatus.Text = "Connected";
unsafe
{
uint rez1 = 2;
uint* rez = &rez1;
string ctrName = "label" + btn_down.ToString();
if (SimpleIOClass.ReadPin(btn_down, rez))
{
if (rez1.ToString() == "1") // poga atlaista
{
// register button press
if (btn_down == Pogas["smaids"]) { OSD(":)"); new Thread(() => SendBtnToServer("1")).Start(); }
if (btn_down == Pogas["neitrals"]) { OSD(":|"); new Thread(() => SendBtnToServer("2")).Start(); }
if (btn_down == Pogas["bedigs"]) { OSD(":("); new Thread(() => SendBtnToServer("3")).Start(); }
if (btn_down == Pogas["smaids2"]) { OSD(":)"); new Thread(() => SendBtnToServer("1")).Start(); }
if (btn_down == Pogas["neitrals2"]) { OSD(":|"); new Thread(() => SendBtnToServer("2")).Start(); }
if (btn_down == Pogas["bedigs2"]) { OSD(":("); new Thread(() => SendBtnToServer("3")).Start(); }
}
}
else this.Controls[ctrName].Invoke(new Action(() => this.Controls[ctrName].Text = "Read pin ERROR (Release)"));
}
}
else
{
lblConnStatus.Text = "NOT Connected";
}
btn_down = 99;
}// CheckUserInput