我有一個方法可以在C#中創建一個運行方法的線程(CallCheckLogic - 如下所示)雖然我已經指定要發生睡眠(Thread.Sleep(60000); )方法(例如ChecksObject.Check1Logic())保持循環,就像睡眠線程方法被忽略一樣。這對我來說不合邏輯,有人能夠解釋爲什麼會發生這種行爲?當被告知這樣做時線程不會睡眠
預期結果:創建一個新線程,方法CallCheckLogic被調用,它自己調用ChecksObject.Check1Logic >> ChecksObject.Check7Logic然後Thread.Sleep(60000);被調用,導致線程休眠60秒,然後運行一個循環,然後再次運行CallCheckLogic。
private void StartCheckerThread()
{
Thread t = new Thread(o =>{CallCheckLogic();});t.Start();
running = true;
}
public void CallCheckLogic()
{
Checks ChecksObject = new Checks();
ChecksObject.Check1Logic();
ChecksObject.Check2Logic();
ChecksObject.Check3Logic();
ChecksObject.Check4Logic();
ChecksObject.Check5Logic();
ChecksObject.Check6Logic();
ChecksObject.Check7Logic();
// This method/delegate parses the outfile of "temp" or rather the results of the tests and turns on/off the appropriate light on the GUI
LightControlDelegate d1 = new LightControlDelegate(lightControl);
this.BeginInvoke(d1);
Thread.Sleep(60000);
//LoopPorts();
}
ChecksObject.Check1Logic方法:
public void Check1Logic()
{
// clean up time!
File.Create("temp").Dispose();
// lets grabs the info from the config!
var lines = File.ReadAllLines("probe_settings.ini");
var dictionary = lines.Zip(lines.Skip(1), (a, b) => new { Key = a, Value = b })
.Where(l => l.Key.StartsWith("#"))
.ToDictionary(l => l.Key, l => l.Value);
// lets define variables and convert the string in the dictionary to int for the sock.connection method!
int portno1;
int.TryParse(dictionary["#PortNo1"], out portno1);
// Convert hostname to IP, performance issue when using an invalid port on a hostname using the TcpClient class!
IPAddress[] addresslist = Dns.GetHostAddresses(hostname2);
foreach (IPAddress theaddress in addresslist)
{
// Attempt to create socket and connect to specified port on host
TcpClient tcP = new System.Net.Sockets.TcpClient();
try
{
tcP.ReceiveTimeout = 1;
tcP.SendTimeout = 1;
tcP.Connect(theaddress, portno1);
tcP.Close();
StreamWriter sw = File.AppendText("temp");
sw.Flush();
sw.WriteLine("Check1=Success");
sw.Close();
}
catch
{
StreamWriter sw = File.AppendText("temp");
sw.WriteLine("Check1=Fail");
sw.Close();
}
}
}
+1爲標題...搞笑:) :) :) – TheBoyan 2011-12-23 12:29:16
但嚴重的是,CallCheckLogic()線程將Sleep()。是什麼讓你覺得它不?你遺漏了循環部分。 – 2011-12-23 12:32:47
因爲,我可以在我的網絡監視器上看到正在使用「ChecksObject.CheckXLogic」方法檢查的遠程端口正在連續(幾乎就像循環的方法一樣),我添加了ChecksObject.Check1Logic方法(它們都很漂亮差不多相同) – Mike 2011-12-23 12:36:47