C#WPF后台工作者 [英] C# WPF Background worker
本文介绍了C#WPF后台工作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在WPF中使用后台工作者?例如,我希望能够像计时器一样使用它,我可以设置时间间隔并告诉它每次循环其自身的时间我想要它做什么
How do i use a background worker in a wpf? like, i want to be able to use it like a timer, i can set the interval and tell it what i want it to do each time it loops its self
推荐答案
当然,请使用System.Threading.Sleep
进行计时.如果您有机会使用线程,请不要使用计时器,这很容易.我会说,一定要避免使用计时器.
现在,您无法从非UI线程在UI上调用任何东西.相反,您将需要调用System.Threading.Dispatcher
的方法Invoke
或BeginInvoke
来调用任何与UI相关的操作.
您将在我以前的文章中找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5的问题 [ C#中的计时器线程 [ ^ ].
另请参阅我的链接集,该链接集是我过去有关线程的答案的链接:
如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].
—SA
Sure, useSystem.Threading.Sleep
for timing. Don''t use a timer if you have any chance to use a thread, which is a lot easier. I would say, avoid timers by all means.
Now, you cannot call anything on UI from non-UI thread. Instead, you will need to call the methodInvoke
orBeginInvoke
ofSystem.Threading.Dispatcher
to invoke any UI-related operation.
You will find detailed explanation of how it works and code samples in my past asnwers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].
My explanation why a timer is no good: Timer Threading in C#[^].
See also my collection of links to my past answers on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].
—SA
先尝试一下,
http://elegantcode .com/2009/07/03/wpf-multithreading-using-the-backgroundworker-and-reporting-the-progress-to-the-ui/ [ Google [ ^ ]以获得更多...
Try it first,
http://elegantcode.com/2009/07/03/wpf-multithreading-using-the-backgroundworker-and-reporting-the-progress-to-the-ui/[^]
Google[^] for more...
这篇关于C#WPF后台工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文