简体   繁体   English

计时器还是线程?

[英]Timer or Thread?

I have a method(say method1) that writes to database(sqlserver)and another method(say method2) that tries to access the same database after some time and updates the data row that was created by method1. 我有一个写入数据库(sqlserver)的方法(say method1)和另一个试图在一段时间后访问同一数据库并更新method1创建的数据行的方法(say method2)。

The problem arises when method1 fails to access db due to the LAN being disconnected (this is not an exception this is a scenario that will definitely arise in my software, getting into details will make the question too complex) if method1 fails to access db method2 cannot work. 当method1无法访问db method2时,由于LAN断开而method1无法访问db时,就会出现问题(这不是例外,在我的软件中肯定会出现这种情况,进入细节会使问题变得过于复杂)。无法工作。

What I want to do is to make method1 store values to local db instead of server if the LAN is disconnected and as soon as it enters value in local db the application should start trying to access the server after ever 10-15 seconds. 我想做的是,如果LAN断开连接,则让method1将值存储到本地db而不是服务器中,并且在本地db中输入值后,应用程序应在10-15秒后开始尝试访问服务器。

What should I use timer or create a new thread? 我应该使用计时器还是创建新线程?

To perform a certain operation after a time interval, Timer is probably the best bet. 要在一个时间间隔后执行某些操作, 计时器可能是最好的选择。

Timer: Generates recurring events in an application. 计时器:在应用程序中生成重复事件。

You need both to have long running (potentially freezing GUI) operation started in some time in the future. 您都需要在将来的某个时间开始长时间运行(可能会冻结GUI)操作。 You use timer to start operation after interval and threads for performing long background operations. 您可以使用计时器在间隔后启动操作,并使用线程来执行长时间的后台操作。

The link below demonstrates in c# a generic polling component that runs at a specified interval and uses a background thread to perform the user action specified. 下面的链接在c#中演示了一个按指定间隔运行的通用轮询组件,该组件使用后台线程执行指定的用户操作。 You can use this operation to check your local DB and perform the necessary operations. 您可以使用此操作来检查本地数据库并执行必要的操作。

Sample usage: 用法示例:

IPoller poller = new UrlPoller(args[0], TimeSpan.FromSeconds(7));
IPolling pollingComponent = new Polling.Core.Polling(poller);
pollingComponent.SubscribeForPollingUpdates(PollingAction);
pollingComponent.Start();

For the code and complete sample see: 有关代码和完整示例,请参见:

http://www.avantprime.com/blog/24/an-example-of-repeating-code-using-a-worker-thread-without-using-timers-c http://www.avantprime.com/blog/24/an-example-of-repeating-code-using-a-worker-thread-without-using-timers-c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM