在windows服务中使用线程异步执行C#方法
我有一个windows服务,每10秒运行一次以执行read方法。Read方法使用构造函数中提供的连接url连接到远程服务器。 如果远程服务器未能响应,它将抛出错误并进行捕获。我们如何使线程重新开始在windows服务中使用线程异步执行C#方法,c#,multithreading,windows-services,C#,Multithreading,Windows Services,我有一个windows服务,每10秒运行一次以执行read方法。Read方法使用构造函数中提供的连接url连接到远程服务器。 如果远程服务器未能响应,它将抛出错误并进行捕获。我们如何使线程重新开始 class PMTicketsService { private Timer _serviceTimer; private TimerCallback _timerDelegate; public PMTicketsService() { Ini
class PMTicketsService
{
private Timer _serviceTimer;
private TimerCallback _timerDelegate;
public PMTicketsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// Set the method to execute when the timer executes.
_timerDelegate = new TimerCallback(Receive);
// Create timer and attach our method delegate to it
_serviceTimer = new Timer(_timerDelegate, null, 1000, 10000);
}
public void Receive(object state)
{
ABC abc = new ABC(Url);
ABC abc1 = new ABC(Url1);
/* Create the thread object, passing in the abc.Read() method
via a ThreadStart delegate. This does not start the thread. */
Thread oThread = new Thread(new ThreadStart(abc.Read());
Thread oThread1 = new Thread(new ThreadStart(abc1.Read());
// Start the thread
oThread.Start();
oThread1.Start();
oThread.Join();
oThread1.Join();
}
}
class ABC
{
public string strUrl;
public ABC(string url)
{
strUrl = url;
}
public void Read()
{
try
{
// Code to use the connectionurl to access a remote server
}
catch (Exception ex)
{
// If the connection url fails to respond, how do we make thread start again?
}
}
}
为什么要开始另一个线程?启动/停止线程是一项昂贵的操作,您最好保持现有线程处于打开状态,并不断尝试连接(可能中间有睡眠)。您已经有了防止线程崩溃的try/catch。只需在一段时间内包装try/catch(!done),并在成功连接后将done设置为true
您可能还想添加一些代码,这样,如果您无法连续连接X次(可能是5次),那么您将停止尝试,或者增加连接尝试之间的超时时间。以后,您应该提交实际编译的示例代码。我拿走了你所有的东西,把它清理干净,去掉了不必要的计时器,并以一种能满足你需要的方式来构建它。在下面的代码中,您的读取方法将继续运行,直到您将
done
设置为true
protected override void OnStart(string[] args)
{
try
{
ABC abc = new ABC("www.abc.com");
// Create the thread object, passing in the abc.Read() method
Thread oThread = new Thread(new ThreadStart(abc.Read));
// Start the thread
oThread.Start();
}
catch (Exception)
{
}
}
public class ABC
{
string strUrl = "";
public ABC(string url)
{
strUrl = url;
}
public void Read()
{
bool done = false;
while (!done)
{
try
{
//Code to use the connectionurl to access a remote server
//Use strUrl in here
}
catch (Exception)
{
//Wait 10 seconds before trying again
Thread.Sleep(10000);
}
//On success, set done to true
done = true;
}
}
}
这段代码可能需要一些清理…@James。如何检查线程中的异常并启动另一个线程。你有代码示例吗?我刚刚非常准确地告诉你需要做什么,而你需要做的与线程无关;所有的线程工作都已经完成了。您需要定义一个布尔值,添加一个while循环,可能还需要添加一个Thread.Sleep。这些是您需要添加的唯一代码行,我已经告诉您需要在哪里添加它们。我完全相信你,你可以把它变成源代码,而不需要从这里的人那里复制/粘贴它。