我试图以恒定的时间间隔读取文件,然后将查询的数据发送到特定的网络服务器。以下是我正在使用的代码,但是服务启动和停止没有做任何事情。我无法弄清楚错误。
public partial class IPTProjectService : ServiceBase
{
private Thread checkingThread;
private System.Timers.Timer timer;
Boolean sendingTime;
public IPTProjectService()
{
InitializeComponent();
checkingThread = new Thread(update);
timer = new System.Timers.Timer(Properties.Settings.Default.TIMEINTERVAL);
timer.Elapsed += timer_Elapsed;
sendingTime = true;
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
setSendingTime();
if (!File.Exists("Testfile.txt"))
{
File.Create("Testfile.txt");
timer_Elapsed(sender, e);
}
else
{
File.WriteAllText("Testfile.txt", timer.ToString());
}
}
private void setSendingTime()
{
sendingTime = true;
}
private void update()
{
while (true)
{
if (sendingTime)
{
CarpoolWebClient.sendData(Properties.Settings.Default.DATAFILE);
sendingTime = false;
}
}
}
protected override void OnStart(string[] args)
{
try
{
timer.Start();
checkingThread.Start();
}
catch (Exception ex)
{
Debug.Fail(ex.ToString());
}
}
protected override void OnStop()
{
try
{
timer.Stop();
checkingThread.Abort();
}
catch(Exception e)
{
StreamWriter writer = new StreamWriter("testfile.txt", true);
writer.Write(e.ToString());
writer.Close();
}
}
}
class CarpoolWebClient
{
public static void sendData(String fileName)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
//URL of message broker
string uri = "http://localhost/IPTProject/receive_xml.php";
req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "text/xml";
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the xml text into the stream
writer.WriteLine(GetTextFromXMLFile(@fileName));
writer.Close();
rsp = req.GetResponse();
}
catch (WebException webEx)
{
//MessageBox.Show(webEx.Message);
throw webEx;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
throw ex;
}
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}
private static string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
}