private void HandleCallback1(IAsyncResult result) { try { SqlCommand command = (SqlCommand)result.AsyncState; var reader = command.EndExecuteReader(result); var del = new DisplayReaderDelegate(AddSupplier); Invoke(del, reader); } catch (Exception ex) { Invoke(new DisplayInfoDelegate(DisplayStatus), String.Format("Ready(last error: {0}", ex.Message)); } finally { isExecuting = false; if (connection != null) { connection.Close(); } } }
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; XmlReader reader = command.EndExecuteXmlReader(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. // 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. DisplayReaderDelegate del = new DisplayReaderDelegate(DisplayProductInfo); this.Invoke(del, reader); } 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 none of // your code is 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 DisplayInfoDelegate(DisplayStatus), String.Format("Ready(last error: {0}", ex.Message)); } finally { isExecuting = false; if (connection != null) { connection.Close(); } } }
private void HandleCallback(IAsyncResult result) { try { var command = (SqlCommand)result.AsyncState; var reader = command.EndExecuteReader(result); var del = new DisplayReaderDelegate(Additems); Invoke(del, reader); } catch (Exception ex) { Invoke(new DisplayInfoDelegate(DisplayStatus),ex.Message); } finally { isExecuting = false; if (connection != null) { connection.Close(); } } }