【发布时间】:2012-01-26 14:39:28
【问题描述】:
我有一个每 10 秒运行一次的 Windows 服务来执行读取方法。 Read 方法使用构造函数中提供的连接 url 连接到远程服务器。 如果远程服务器没有响应,它会抛出错误并去捕获。我们如何让线程重新开始?
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?
}
}
}
【问题讨论】:
-
这段代码可以进行一些清理...
-
@詹姆斯。您如何检查线程中的异常并启动另一个线程。你有代码示例吗?
标签: c# multithreading windows-services