如何在System.Timer.Timers中启动线程 [英] How to start thread in System.Timer.Timers

查看:99
本文介绍了如何在System.Timer.Timers中启动线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用System.Timer.Timers从表中获取和处理数据.此对象中的所有步骤:

-步骤1:从表格中获取所有数据并返回数组
-步骤2:foreach返回数组和过程数据.

在第二步中,我想使用线程处理数据,但是我的程序出错????

您能帮我吗??????????

解决方案

为什么要尝试使用计时器?

您确实意识到计时器每次到达间隔都会触发,不是吗?所以您将计时器设置为100毫秒,它将每秒触发十次...


您要达到什么目的,以为您认为需要此功能?循环:从数据库获取数据;处理数据;呼叫System.Thread.Sleep(delayMs);选择5秒或更短的delayMs.就这样.

尽量避免使用计时器.在很多情况下,您不希望使用线程计时器,线程比线程容易得多,功能也更强大.在这种情况下,您当然应该摆脱计时器.

您可能需要从数据处理线程通知UI线程.由于无法从非UI线程调用任何UI属性,因此需要调用方法InvokeBeginInvokeSystem.Threading.Dispatcher(适用于WPF和Forms)或System.Windows.Forms.Control(仅适用于Forms). />
在我过去的答案中,您会找到有关其工作原理的详细说明以及用法说明.在此答案中,您将找到与我过去有关相关主题的答案相关的参考文献集:
如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

—SA


I use System.Timer.Timers to get and process data from table. All step in this object:

- Step 1: get all data from table and return array
- Step 2: foreach return array and process data.

In the second step, i want to use threading to process data but my program is error????

Can you help me?????????

解决方案

Why are you trying to use a timer?

You do realise that a timer fires every time it gets to the interval, don''t you? so it you set up a timer for 100 milliseconds, it will fire ten times a second...


What are you trying to achieve that you think needs this?


You need to use just one extra thread, created and use it for the whole run time of your application, it should run an infinite loop: get data from database; process data; call System.Thread.Sleep(delayMs); choose delayMs 5 sec or less. That''s all.

Try to avoid using timers. There are not many situations when you can prefer timer of thread, threads are much easier and much more robust then threads. In you case, you most certainly should get rid of the timer.

You will probably need to notify your UI thread from your data processing thread. As you cannot call any UI properties from non-UI thread, you will need to call the method Invoke or BeginInvoke or System.Threading.Dispatcher (works with both WPF and Forms) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and usage directions in my past answers. In this answer you will find a collection of relevant references to my past answers on related topics:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


这篇关于如何在System.Timer.Timers中启动线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆