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?
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:
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). 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 :) :)
you can also use BackgroundWorker for this in case you require any updation on the UI for progress and completion.