vb.net - Suspend a thread while waiting for events -
i trying use separate thread handle specific events in vb.net. idea being not want main application held if particular event handler takes awhile finish. how main thread loop suspend thread while allowing handle events when occur?
when create windows forms application, there ui thread handles ui events. not imagine thread continuously polling variable see if has pressed button. imagine thread suspended until os tells there do. trying figure out how ensure event handlers not being executed ui thread. have read, can raising events different thread. thread while waiting other events, exit?
i wanted know how create thread works ui thread, processes events want process. not sure how events work in .net. understand event handlers run on thread raises event. believe .net allocates threads thread pool process events such timer events. not clear on how works, though, , threads doing when not handling events.
based on comments can see want can best solved using producer-consumer pattern. pattern consumer thread constructed , started in such manner spins around loop indefinitely waiting items appear in queue. ui thread use same pattern implement message loop. here how works.
public class dedicatedprocessingthread { private blockingcollection<object> m_queue = new blockingcollection<object>(); public consumer() { new thread( () => { while (true) { object item = m_queue.take(); // blocks until item appears. // item here. } }).start(); } public void post(object item) { m_queue.add(item); } }
the magic happens in take
method. method designed "suspend" (your terminology, not mine) or change state of thread waitsleepjoin
while queue empty. once item queued consuming thread wakes , take
method returns next item. general pattern used in message loop of ui thread except instead of queueing plain old object
instances windows posting system.windows.forms.message
values. similar posting delegate
instances processed on consumer thread once arrive.
Comments
Post a Comment