惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
博客园_首页
H
Help Net Security
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
B
Blog
I
InfoQ
SecWiki News
SecWiki News
T
Tailwind CSS Blog
Spread Privacy
Spread Privacy
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
P
Palo Alto Networks Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Vercel News
Vercel News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
Kaspersky official blog
M
MIT News - Artificial intelligence
S
Schneier on Security
T
Threat Research - Cisco Blogs
F
Fortinet All Blogs
Cyberwarzone
Cyberwarzone
Scott Helme
Scott Helme
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
The Cloudflare Blog
Recent Announcements
Recent Announcements
Security Latest
Security Latest
G
GRAHAM CLULEY
IT之家
IT之家
Y
Y Combinator Blog
The Last Watchdog
The Last Watchdog
腾讯CDC
Google DeepMind News
Google DeepMind News
V
V2EX
S
Securelist
TaoSecurity Blog
TaoSecurity Blog
B
Blog RSS Feed
S
SegmentFault 最新的问题
博客园 - 叶小钗
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
Project Zero
Project Zero
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
F
Full Disclosure

博客园 - enjoy .net

visual basic video series:Forms over data 无功倒送问题 变压器高低压侧的电流计算 爬电、爬距(泄漏距离)、爬电比距 VS2005的初体验 地板选购指南 IT服务管理时代已经到来 IT服务管理的效果分析 How to use the Install from Media feature to promote Windows Server 2003-based domain controllers 70-294读书笔记 TechED上海 术语: Tombstone/Tombstone Lifetime Windows 2003故障恢复 几乎没有管理的国企! ASP.Net 2.0中的Membership,Role和Profile 关于ASP.Net 2.0中的Theme ntdsutil的功能 体验了一次DNS的动态更新功能 Flexible Single Master Operations (FSMO)
使用BackgroundWorker进行Thread编程
enjoy .net · 2005-11-06 · via 博客园 - enjoy .net

当用户执行一个非常耗时的操作时,如果不借助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