[英]Can I place the mouse event handler on a separate thread?
Can I put a thread on a mouse event handler? 我可以在鼠标事件处理程序上放一个线程吗?
Calls_Calls.MouseUp += new MouseEventHandler(Calls_Calls_MouseUp);
How to add a thread over this? 如何在此添加线程?
I would set up the event handler in the same way, but in the Calls_Calls_MouseUp
method you can launch a thread to do the work: 我会以相同的方式设置事件处理程序,但在
Calls_Calls_MouseUp
方法中,您可以启动一个线程来完成工作:
private void Calls_Calls_MouseUp(object sender, MouseEventArgs e)
{
ThreadPool.QueueUserWorkItem(state => {
// do the work here
});
}
However, I typically try to have my event handlers as unaware as possible, just calling some other method, often based on some condition: 但是,我通常会尝试尽可能不知道我的事件处理程序,只是调用其他方法,通常基于某些条件:
private void Calls_Calls_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DoSomething();
}
}
private void DoSomething()
{
ThreadPool.QueueUserWorkItem(state => {
// do the work here
});
}
This gives you the ability to trigger the exact same behavior from something else than the MouseUp
event on a certain control (so that you can have the same behavior on a menu item, a toolbar button and perhaps a regular command button). 这使您能够从某个控件上的
MouseUp
事件触发完全相同的行为(因此您可以在菜单项,工具栏按钮和可能的常规命令按钮上具有相同的行为)。 It may also open up the possibility to have unit tests on the functionality (even though that is somewhat trickier with asynchronous code). 它还可能开启对功能进行单元测试的可能性(即使这对于异步代码来说有些棘手)。
Calls_Calls.MouseUp+= new MouseEventHandler(delegate(System.Object o, System.EventArgs e) { new Thread(Calls_Call_MouseUp).Start(); });
should work for you. 应该适合你。 If you get brackets errors, fix them since I handwrote the code :) :)
如果你得到括号错误,修复它们,因为我手写代码:) :)
如果您需要在UI上进行任何更新以获得进度和完成,您还可以使用BackgroundWorker 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.