Asynchronous Mode in .NET


In this section, We'll discuss the popular issues of asynchronous mode in .NET.

In the Visual Basic 6.0, we usually catch the events like the following codes:

Private Sub m_oSmtp_OnConnected()
    status.Text = "connected" 'status is a TextBox control
End Sub

However, if we use above code to catch the events in .NET framework, a "Illegal cross-thread operation" exception will be thrown while this event is fired. Why? Because ANSMTP fires the event from another worker-thread, that means all codes in the event is running in the worker thread, above code try to change the Text property of the TextBox control in the event, but accessing Windows Control directly from another thread is denied in .NET framework, so a "Illegal cross-thread operation" exception is thrown.

Fortunately, .NET framework provides a method named "BeginInvoke" for Windows.Control class. This method can access the Windows Control from any thread. Therefore, we can use BeginInvoke method to access the Windows Control in .NET framework to avoid this exception.

How to use BeginInvoke method.

Protected Delegate Sub UpdateStatusTextDelegate(ByVal val As String)
 
Private Sub m_oSmtp_OnConnected()
    ThreadUpdateStatusText("Connected")
End Sub
     
Protected Sub ThreadUpdateStatusText(ByVal val As String)
    If InvokeRequired Then
        Dim args(0) As Object
        args(0) = val
        Dim d As New UpdateStatusTextDelegate(AddressOf ThreadUpdateStatusText)
        BeginInvoke(d, args)
        Exit Sub
    End If
    status.Text = val
End Sub     

To learn more about asynchronous mode, please refer to rich samples in ANSMTP installation package.


2001-2007 © Copyright AdminSystem Software Limited. All rights reserved.