当线程被告知这样做时,它没有睡觉
本文关键字:线程 被告 这样做 | 更新日期: 2023-09-27 18:18:45
我有一个方法,在c#中创建一个线程,运行一个方法(CallCheckLogic -如下所示)虽然我已经指定了一个睡眠发生(thread . sleep(60000);)的方法(例如checksoobject . check1logic())保持循环,它就像睡眠线程方法被忽略。这对我来说没有逻辑意义,有人能解释一下为什么会发生这种行为吗?
预期结果:创建一个新线程,调用CallCheckLogic方法,该方法本身调用ChecksObject。Check1Logic>> ChecksObject。Check7Logic然后是Thread.Sleep(60000);调用CallCheckLogic,导致线程休眠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。
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();
}
}
}
我没有看到任何循环。你的CallCheckLogic
方法被调用一次,然后它结束,线程停止执行。也许在你的CheckXLogic
中有一个无限循环,所以你的线程似乎一直在工作,但我可以说它不太可能有一个Sleep调用的问题。
尝试在Sleep
之前和之后添加断点,您将知道这行代码是否被执行。