WPF:如何调用一个方法在单独的线程用的延迟时间 [英] WPF: how to invoke a method in a separate thread with a delay time

查看:470
本文介绍了WPF:如何调用一个方法在单独的线程用的延迟时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框用户可以在其中输入搜索项。它绑定到字符串期限属性在我的视图模型。我想,当其含量变化做一搜索查询。但我想用拖延地查询在一个单独的线程

I have a TextBox that user can enter search-term in it. Its bind to string Term property in my view-model. And I want to do a search query when its content changed. But I want to do the query in a separate thread with a delay.

例如。当用户键入一个字母,我要等待的0.3秒后,如果用户此时(0.4秒)内更改输入,定时器的重置和启动一次。否则,我开始一个新的线程并执行搜索查询。当执行查询时,如果用户再次更改期限,终止上一个查询并再次启动。

e.g. when user type a letter, I want to wait for 0.3 second, and if user change the input within this time (0.3 second), the timer resets and starts again. Otherwise, I start a new thread and do the search query. While query is executing, if user change the term again, abort prev query and start again.

我知道如何在Windows的形式与线程做到这一点,定时类。但是,我是新来的 WPF 和我在寻找是否有线程功能为WPF指定的方式(或者可能是一个更好的表现的一种方式)。

I know how to do this in windows-forms with threading and Timer class. But I'm new to WPF and I'm searching if there is a way specified for WPF threading functionality (or may be a way with a better performance).

你有什么想法?你能帮助我吗?

Have you any idea? Can you help me?

推荐答案

您可以使用的 DispatcherTimer 。在每个按键,停止,如果它已经运行的计时器,然后启动它。我的认为的(你应该检查这个!),这将重新设置。

You could use DispatcherTimer. On each keypress, stop the timer if it's already running, then start it. I believe (and you should check this!) that that will reset it.

如果它触发,你再取的电流值文本框,并开始在一个单独的线程执行操作(例如,使用 Task.Factory.StartNew ,如果你使用.NET 4,或 BackgroundWorker的,或者只是创建一个新的线程)。

If it fires, you then take the current value in the textbox and start performing the operation in a separate thread (e.g. using Task.Factory.StartNew, if you're using .NET 4, or BackgroundWorker, or just creating a new thread).

基本上是从我真的想要做的事分离新线程的一部分部分,保持UI线程上的一切,直到你到哪儿去决定的时候,你真正的的想要做的事(你知道你要使用的值)。

Basically that separates the "new thread" part from the "do I really want to do something" part, keeping everything on the UI thread until the point where you've decided you really do want to do something (and you know the value you want to use).

这篇关于WPF:如何调用一个方法在单独的线程用的延迟时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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