使用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一起使用


代码如下所示:
ExpandedBlockStart.gif ContractedBlock.gif   Private   Sub Button1_Click() Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
InBlock.gif
InBlock.gif        
If My.Computer.Network.IsAvailable Then
InBlock.gif
InBlock.gif            
Me.ListView1.View = View.Details
InBlock.gif            
Me.ListView1.Items.Clear()
InBlock.gif            
Me.ListView1.Columns.Clear()
InBlock.gif            ListView1.Columns.Add(
New ColHeader("IP Address"110, HorizontalAlignment.Left, True))
InBlock.gif            ListView1.Columns.Add(
New ColHeader("Is On Line"50, HorizontalAlignment.Left, True))
InBlock.gif            
'/
InBlock.gif
            '1、调用BackgroundWorker的RunWorkerAsync方法(可以传递参数),它将调用DoWork事件
InBlock.gif
            BackgroundWorker1.RunWorkerAsync(Me.TextBox1.Text)
InBlock.gif
InBlock.gif            
InBlock.gif        
Else
InBlock.gif            
MsgBox("网络不通,测试无法进行", MsgBoxStyle.Information)
InBlock.gif        
End If
ExpandedBlockEnd.gif    
End Sub

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

None.gif    
' 耗时的操作
ExpandedBlockStart.gifContractedBlock.gif
     Private   Function PingIPs() Function PingIPs(ByVal str As String, _
InBlock.gif        
ByVal worker As BackgroundWorker, _
InBlock.gif        
ByVal e As DoWorkEventArgs) As String
InBlock.gif
InBlock.gif        
' Abort the operation if the user has canceled.
InBlock.gif
        ' Note that a call to CancelAsync may have set 
InBlock.gif
        ' CancellationPending to true just after the
InBlock.gif
        ' last invocation of this method exits, so this 
InBlock.gif
        ' code will not have the opportunity to set the 
InBlock.gif
        ' DoWorkEventArgs.Cancel flag to true. This means
InBlock.gif
        ' that RunWorkerCompletedEventArgs.Cancelled will
InBlock.gif
        ' not be set to true in your RunWorkerCompleted
InBlock.gif
        ' event handler. This is a race condition.
InBlock.gif
        Dim res As String
InBlock.gif
InBlock.gif        
Dim i As Integer
InBlock.gif
InBlock.gif        
For i = 1 To 50
InBlock.gif            
'/
InBlock.gif
            '3、在耗时操作中判断CancellationPending属性,如果为false则退出
InBlock.gif
            If worker.CancellationPending Then
InBlock.gif                e.Cancel 
= True
InBlock.gif                
Exit Function
InBlock.gif            
Else
InBlock.gif                
If My.Computer.Network.Ping(str & i) Then
InBlock.gif                    res 
= ""
InBlock.gif                
Else
InBlock.gif                    res 
= "不通"
InBlock.gif                
End If
InBlock.gif            
End If
InBlock.gif            
'4、如果要向用户界面发送信息,则调用ReportProgress方法,它将调用ProgressChanged(可以将改变同过object类型传递)
InBlock.gif
            worker.ReportProgress(i, res & "|" & str & i)
InBlock.gif        
Next i
InBlock.gif
ExpandedBlockEnd.gif    
End Function

None.gif    
' /
None.gif
     ' 5、在ProgressChanged事件的响应代码中将改变呈现给用户
ExpandedBlockStart.gifContractedBlock.gif
     Private   Sub BackgroundWorker1_ProgressChanged() Sub BackgroundWorker1_ProgressChanged(ByVal sender As ObjectByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
InBlock.gif        
Dim item As New ListViewItem
InBlock.gif        
Dim userdata As String
InBlock.gif        
Dim userdataarr() As String
InBlock.gif        userdata 
= e.UserState
InBlock.gif        userdataarr 
= userdata.Split("|")
InBlock.gif
InBlock.gif        item.Text 
= userdataarr(1)
InBlock.gif        item.SubItems.Add(userdataarr(
0))
InBlock.gif
InBlock.gif
InBlock.gif        
Me.ListView1.Items.Add(item)
InBlock.gif        
Me.ListView1.Columns(0).Width = -2
InBlock.gif        
Me.ListView1.Columns(1).Width = -2
ExpandedBlockEnd.gif    
End Sub

None.gif
None.gif    
' /
None.gif
     ' 6、如果需要取消耗时操作,则调用BackgroundWorker的CancelAsync方法,需要和步骤3一起使用
ExpandedBlockStart.gifContractedBlock.gif
     Private   Sub Button2_Click() Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
InBlock.gif        
Me.BackgroundWorker1.CancelAsync()
ExpandedBlockEnd.gif    
End Sub

转载于:https://www.cnblogs.com/chinapro/archive/2005/11/06/270169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值