计时器与重复的后台工作者 [英] Timer vs. repetitive background worker

查看:74
本文介绍了计时器与重复的后台工作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Windows Forms应用程序,该应用程序在指定的时间间隔后调用WCF服务,并根据从该服务接收的数据显示输出.我计划将计时器用于此目的,以便在500毫秒后调用该WCF服务方法.但是我的一些同事告诉我使用后台工作程序,然后在Work_Completed事件中重新运行工作程序.我想知道两者之间的区别是什么?计时器还会创建后台线程吗?哪个最适合长时间运行的任务?

I am developing a Windows Forms application that calls a WCF service after a specified interval and shows output according to the data received from the service. I had a plan to use timer for this purpose that calls that WCF service method after 500 msec. But some of my colleagues told me to use background worker and then on Work_Completedevent re-run the Worker. I want to know what is the difference between these two? Does timer also creates a background thread? Which one is best suited for long running tasks?

推荐答案

就资源消耗而言,Timer几乎肯定更合适. BackgroundWorker将仅为该任务创建一个新线程.创建一个新线程是一个相当昂贵的操作.尽管有许多不同的计时器实现,并且它们的实现会有所不同,但它们通常将依赖于OS工具来定期触发事件,这将比启动一个新的专用线程更好.

A Timer is almost certainly more suitable in terms of resource consumption. A BackgroundWorker is going to create a new thread just for that task. Creating a new thread is a fairly expensive operation. While there are many different timer implementations, and their implementations will vary, they are generally going to be reliant on OS tools that will fire an event periodically, which is going to be preferable to starting up a new dedicated thread.

Timer对象中的大多数关键区别在于它们准备就绪"时的工作.一些创建一个新的线程池线程.有些具有专用的线程,计时器的所有实例都共享该线程以运行处理程序,有些将代码编组到UI线程(或其他同步上下文),而您可能想要的就是后者.如果您使用的计时器在您使用的特定UI框架中可用,那么您将看到它的行为.

Most of the key differences in Timer objects is what they do when they're "ready". Some create a new thread pool thread; some have a dedicated thread that is shared by all instances of the timer to run the handler(s), some marshal the code to the UI thread (or some other synchronization context) and it's the latter that you probably want. If you use the timer that is made available in the particular UI framework that you're using it's the behavior that you'll see.

这篇关于计时器与重复的后台工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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