简体   繁体   中英

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:

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 :) :)

如果您需要在UI上进行任何更新以获得进度和完成,您还可以使用BackgroundWorker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM