private void RealTimeProcessing(object state) { try { FillGridDelegate del = new FillGridDelegate(Test); this.Invoke(del, state); Thread.Sleep(20); //Operation_Audition.BuildDataTable(this.m_ClientEvent, mResult, this.dataGridView1, out iPageCount); } catch (Exception ex) { } }
private void HandleCallback(IAsyncResult result) { try { // Retrieve the original command object, passed // to this procedure in the AsyncState property // of the IAsyncResult parameter. SqlCommand command = (SqlCommand)result.AsyncState; SqlDataReader reader = command.EndExecuteReader(result); // You may not interact with the form and its contents // from a different thread, and this callback procedure // is all but guaranteed to be running from a different thread // than the form. Therefore you cannot simply call code that // fills the grid, like this: // FillGrid(reader); // Instead, you must call the procedure from the form's thread. // One simple way to accomplish this is to call the Invoke // method of the form, which calls the delegate you supply // from the form's thread. FillGridDelegate del = new FillGridDelegate(FillGrid); this.Invoke(del, reader); // Do not close the reader here, because it is being used in // a separate thread. Instead, have the procedure you have // called close the reader once it is done with it. } catch (Exception ex) { // Because you are now running code in a separate thread, // if you do not handle the exception here, none of your other // code catches the exception. Because there is none of // your code on the call stack in this thread, there is nothing // higher up the stack to catch the exception if you do not // handle it here. You can either log the exception or // invoke a delegate (as in the non-error case in this // example) to display the error on the form. In no case // can you simply display the error without executing a delegate // as in the try block here. // You can create the delegate instance as you // invoke it, like this: this.Invoke(new DisplayStatusDelegate(DisplayStatus), "Error: " + ex.Message); } finally { isExecuting = false; } }