Can I put a mouse event handler in a separate thread?

Can I put a stream in a mouse event handler?

Calls_Calls.MouseUp += new MouseEventHandler(Calls_Calls_MouseUp); 

How to add stream through this?

+4
source share
3 answers

I would set up an event handler in the same way, but in the Calls_Calls_MouseUp method Calls_Calls_MouseUp you can start the thread to do the work:

 private void Calls_Calls_MouseUp(object sender, MouseEventArgs e) { ThreadPool.QueueUserWorkItem(state => { // do the work here }); } 

However, as a rule, I try to ensure that my event handlers are not as aware as possible, simply by 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 same behavior from something other than the MouseUp event on a specific control (so that you can have the same behavior in a menu item, a toolbar button, and possibly a regular control button). It may also open up the possibility of conducting unit tests of functionality (although this is somewhat more complicated with asynchronous code).

+3
source
 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 errors in brackets, correct them since I wrote the code :) :)

+1
source

you can also use BackgroundWorker to do this if you need an update in the user interface to complete and complete.

+1
source

Source: https://habr.com/ru/post/1341954/


All Articles