Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm assuming some event in the GUI requires some long-running task to start which be run in the background - there are two main ways to do this. If you simply want to call a method on a different thread then you can do it by <a href="http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx" rel="nofollow noreferrer">Calling Synchronous Methods Asynchronously</a>. I usually do something like this:</p> <pre><code> //delegate with same prototype as the method to call asynchrously delegate void ProcessItemDelegate(object item); //method to call asynchronously private void ProcessItem(object item) { ... } //method in the GUI thread private void DoWork(object itemToProcess) { //create delegate to call asynchronously... ProcessItemDelegate d = new ProcessItemDelegate(this.ProcessItem); IAsyncResult result = d.BeginInvoke(itemToProcess, new AsyncCallback(this.CallBackMethod), d); } //method called when the async operation has completed private void CallbackMethod(IAsyncResult ar) { ProcessItemDelegate d = (ProcessItemDelegate)ar.AsyncState; //EndInvoke must be called on any delegate called asynchronously! d.EndInvoke(ar); } </code></pre> <p>Be aware when using this method that the callback is executed on the background thread, so any updates to the GUI must be done using Invoke.</p> <p>Alternatively you could use shared state to communicate between threads and use an <a href="http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx" rel="nofollow noreferrer">EventWaitHandle</a> to signal updates to the shared state - in this example a method in the GUI adds work items to a queue to be handled in the background. The worker thread processes items from the queue when work becomes available.</p> <pre><code> //shared state private Queue workQueue; private EventWaitHandle eventHandle; //method running in gui thread private void DoWork(Item itemToProcess) { //use a private lock object instead of lock... lock(this.workQueue) { this.workQueue.Add(itemToProcess); this.eventHandle.Set(); } } //method that runs on the background thread private void QueueMonitor() { while(keepRunning) { //if the event handle is not signalled the processing thread will sleep here until it is signalled or the timeout expires if(this.eventHandle.WaitOne(optionalTimeout)) { lock(this.workQueue) { while(this.workQueue.Count > 0) { Item itemToProcess = this.workQueue.Dequeue(); //do something with item... } } //reset wait handle - note that AutoResetEvent resets automatically this.eventHandle.Reset(); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload