使用BackgroundWorker进行Thread编程

当用户执行一个非常耗时的操作时,如果不借助Thread编程,用户就会感觉界面反映很迟钝。在.Net 2.0中可以通过BackgroundWork非常方便地进行Thread编程,大致的步骤是:
1、调用BackgroundWorker的RunWorkerAsync方法(可以传递参数),它将调用DoWork事件
2、在DoWork的事件响应代码中调用耗时的操作,此例中是PingIPs函数
3、在耗时操作中判断CancellationPending属性,如果为false则退出
4、如果要向用户界面发送信息,则调用BackgroundWorker的ReportProgress方法,它将调用ProgressChanged事件(可以将改变通过object类型传递)
5、在ProgressChanged事件的响应代码中将改变呈现给用户
6、如果需要取消耗时操作,则调用BackgroundWorker的CancelAsync方法,需要和步骤3一起使用


代码如下所示:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        
If My.Computer.Network.IsAvailable Then

            
Me.ListView1.View = View.Details
            
Me.ListView1.Items.Clear()
            
Me.ListView1.Columns.Clear()
            ListView1.Columns.Add(
New ColHeader("IP Address"110, HorizontalAlignment.Left, True))
            ListView1.Columns.Add(
New ColHeader("Is On Line"50, HorizontalAlignment.Left, True))
            
'/////////////////////////////////////////////////////
            '1、调用BackgroundWorker的RunWorkerAsync方法(可以传递参数),它将调用DoWork事件
            BackgroundWorker1.RunWorkerAsync(Me.TextBox1.Text)

            
        
Else
            
MsgBox("网络不通,测试无法进行", MsgBoxStyle.Information)
        
End If
    
End Sub




    
'/////////////////////////////////////////////////////
    '2、在DoWork的事件响应代码中调用耗时的操作,此例中是PingIPs函数
    Private Sub BackgroundWorker1_DoWork(ByVal sender As ObjectByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        
' Assign the result of the computation
        ' to the Result property of the DoWorkEventArgs
        ' object. This is will be available to the 
        ' RunWorkerCompleted eventhandler.
        e.Result = PingIPs(e.Argument, worker, e)
    
End Sub

    
'耗时的操作
    Private Function PingIPs(ByVal str As String, _
        
ByVal worker As BackgroundWorker, _
        
ByVal e As DoWorkEventArgs) As String

        
' Abort the operation if the user has canceled.
        ' Note that a call to CancelAsync may have set 
        ' CancellationPending to true just after the
        ' last invocation of this method exits, so this 
        ' code will not have the opportunity to set the 
        ' DoWorkEventArgs.Cancel flag to true. This means
        ' that RunWorkerCompletedEventArgs.Cancelled will
        ' not be set to true in your RunWorkerCompleted
        ' event handler. This is a race condition.
        Dim res As String

        
Dim i As Integer

        
For i = 1 To 50
            
'/////////////////////////////////////////////////////
            '3、在耗时操作中判断CancellationPending属性,如果为false则退出
            If worker.CancellationPending Then
                e.Cancel 
= True
                
Exit Function
            
Else
                
If My.Computer.Network.Ping(str & i) Then
                    res 
= ""
                
Else
                    res 
= "不通"
                
End If
            
End If
            
'4、如果要向用户界面发送信息,则调用ReportProgress方法,它将调用ProgressChanged(可以将改变同过object类型传递)
            worker.ReportProgress(i, res & "|" & str & i)
        
Next i

    
End Function

    
'/////////////////////////////////////////////////////
    '5、在ProgressChanged事件的响应代码中将改变呈现给用户
    Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As ObjectByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        
Dim item As New ListViewItem
        
Dim userdata As String
        
Dim userdataarr() As String
        userdata 
= e.UserState
        userdataarr 
= userdata.Split("|")

        item.Text 
= userdataarr(1)
        item.SubItems.Add(userdataarr(
0))


        
Me.ListView1.Items.Add(item)
        
Me.ListView1.Columns(0).Width = -2
        
Me.ListView1.Columns(1).Width = -2
    
End Sub


    
'/////////////////////////////////////////////////////
    '6、如果需要取消耗时操作,则调用BackgroundWorker的CancelAsync方法,需要和步骤3一起使用
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        
Me.BackgroundWorker1.CancelAsync()
    
End Sub
posted on 2005-11-06 19:25  enjoy .net  阅读(853)  评论(0编辑  收藏  举报