我有带有一些后台处理的多线程应用程序。它有长时间运行的 UI 更新(在 UI 线程本身上),它们是通过众所周知的从后台线程调用的MSDN 上的资源 http://msdn.microsoft.com/en-us/library/757y83z4%28VS.71%29.aspx。我无法缩短这些 UI 更新,因为它们最终是在外部库中完成的 (1)。
现在,从那个后台线程,我想异步调用(使用BeginInvoke()
)这些更新在 UI 线程上进行,但前提是先前的更新尚未完成。如果没有,我想跳过此更新。这将防止 Windows 消息队列溢出,以防调用速度快于被调用方法的执行速度。
我目前的解决方案是这样的:在 UI 线程上执行的方法中,我确实进入和退出 ReaderWriterLockSlim 实例。在后台线程上,我尝试以零超时进入实例。成功后,我调用“BeginInvoke()”,然后再次退出。如果不成功,我会完全跳过方法调用。
public void Update(double x, double y)
{
_updateLock.EnterWriteLock();
try
{ //...long running task... }
finally
{ _updateLock.ExitWriteLock(); }
}
//....
void Provider_PositionChanged(object sender, SpecialEventArgs e)
{
if (_updateLock.TryEnterWriteLock(0)) //noone is currently executing an update?
{
try { myUiControl.BeginInvoke(/*...*/); }
finally { _updateLock.ExitWriteLock(); }
}
这一切都有效,但是有更优雅的解决方案吗?如何从一个线程简单地测试某个方法是否在任何(其他)线程上执行?
- 注意:使用
Invoke()
(代替BeginInvoke()
)不是一个选项,因为这会阻塞我的后台线程,阻止其他东西在那里执行。
- (1)它是 MapXtreme,一个地图解决方案,我想要平移/缩放大型位图地形数据,并更新一些功能。
- 附言。这个问题有些相关,但涵盖了不同的方面:Winforms 多线程:每次在 UI 线程上调用方法时是否需要创建一个新的委托? https://stackoverflow.com/questions/4283689/winforms-multithreading-is-creating-a-new-delegate-each-time-when-invoking-a-met
感谢您的任何答复!
UPDATE:汉斯·帕桑特(Hans Passant)帮助我回答了他的问题。请参阅下面的解决方案。希望这对其他人也有帮助。
/// <summary>
/// This class enqueues asynchronously executing actions (that are running on another thread), but allows
/// to execute only one action at a time. When busy, newly enqueued actions are dropped.
/// Any enqueued action is required to call Done() on this when it has finished, to allow further actions
/// to execute afterwards.
/// </summary>
/// <remarks>This class is intended to help prevent stacking UI-Updates when the CPU or other resources
/// on the machine are not able to handle the amount of updates requested. However, the user
/// must keep in mind, that using this class may result
/// in dropped updates and that the last requested update is not always executed.</remarks>
public class ActionBouncer
{
/// <summary>
/// A event that signals the idle/busy state. Idle means, that no action is currently executing.
/// </summary>
private ManualResetEvent _idle = new ManualResetEvent(true);
/// <summary>
/// Enqueues the specified action, executing it when this bouncer
/// is currently idle.
/// </summary>
/// <param name="action">The action.</param>
public void Enqueue(Action action)
{
if (_idle.WaitOne(0)) //are we idle now? (Remark: This check and the reset below is not thread-safe (thanks to s.skov))
{
_idle.Reset(); //go to busy state
action(); //execute the action now.
}//else drop the action immediately.
}
/// <summary>
/// Signal the bouncer, that the currently executing asynchronous action is done, allowing
/// subsequent requests to execute.
/// This must get explicitly called (in code) at the end of the asynchronous action.
/// </summary>
public void Done()
{
_idle.Set();
}
}