VB.Net程序设计:一个单独的线程-BackgroundWorker例子。搜索目录下的文件。
2008-04-08 11:51
330 查看
来源:Form: http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22479449.html
This code sample assumes that the form has the following controls on it:( 需要的控件:)
TextBox called txtSearchPath
TextBox called txtSearchPattern
Label called lblMessage
Button called btnStart 注意这个按钮的.text属性为:“Start”
ListBox called lstFiles
Imports System.IO
Public Class SearchFilesFrmClass SearchFilesFrm
' To set up for a background operation, add an event handler for the DoWork event.
' Call your time-consuming operation in this event handler. To start the operation,
' call RunWorkerAsync. To receive notifications of progress updates, handle the
' ProgressChanged event. To receive a notification when the operation is completed,
' handle the RunWorkerCompleted event.
' Note
' You must be careful not to manipulate any user-interface objects in your DoWork
' event handler. Instead, communicate to the user interface through the
' ProgressChanged and RunWorkerCompleted events.
' If your background operation requires a parameter, call RunWorkerAsync with your
' parameter. Inside the DoWork event handler, you can extract the parameter from
' the DoWorkEventArgs.Argument property.
' Store the results of the search
Private Files As List(Of String)
' Used to prevent nested calls to ProgressChanged
Private CallInProgress As Boolean
' The Worker thread
Private WithEvents BgWorker As New System.ComponentModel.BackgroundWorker
Private Sub SearchFilesFrm_Load()Sub SearchFilesFrm_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
' Enable ProgressChanged and Cancellation mothed
BgWorker.WorkerReportsProgress = True
BgWorker.WorkerSupportsCancellation = True
End Sub
' Start and Stop the search
Private Sub btnStart_Click()Sub btnStart_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnStart.Click
If btnStart.Text = "Start" Then
If Not Directory.Exists(txtSearchPath.Text.Trim()) Then
MessageBox.Show("The Search Directory does not exist", _
"Path Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
If txtSearchPattern.Text.Trim() = "" Then txtSearchPattern.Text = "*"
Dim arguments() As String = {txtSearchPath.Text.Trim(), _
txtSearchPattern.Text.Trim()}
lstFiles.Items.Clear()
' Start the background worker thread. Thread runs in DoWork event.
BgWorker.RunWorkerAsync(arguments)
btnStart.Text = "Stop"
Else
BgWorker.CancelAsync()
End If
End Sub
' Start the Asynchronous file search. The background thread does it work from
' this event.
Private Sub BgWorker_DoWork()Sub BgWorker_DoWork(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BgWorker.DoWork
'Retrieve the search path which was requested
Dim path As String = DirectCast(e.Argument, String())(0)
Dim pattern As String = DirectCast(e.Argument, String())(1)
' Invoke the worker procedure
Files = New List(Of String)
SearchFiles(path, pattern)
' Return a result to the RunWorkerCompleted event
Dim message As String = String.Format("Found {0} Files", Files.Count)
e.Result = message
End Sub
' Recursively search directory and sub directories
Private Sub SearchFiles()Sub SearchFiles(ByVal path As String, ByVal pattern As String)
' Displat message
Dim message As String = String.Format("Parsing Directory {0}", path)
BgWorker.ReportProgress(0, message)
'Read the files and if the Stop button is pressed cancel the operation
For Each fileName As String In Directory.GetFiles(path, pattern)
If BgWorker.CancellationPending Then Return
Files.Add(fileName)
Next
For Each dirName As String In Directory.GetDirectories(path)
If BgWorker.CancellationPending Then Return
SearchFiles(dirName, pattern)
Next
End Sub
' The bacground thread calls this event when you make a call to ReportProgress
' It is OK to access user controls in the UI from this event.
' If you use a Progress Bar or some other control to report the tasks progress
' you should avoid unnecessary calls to ReportProgress method because this causes
' a thread switch which is a relatively expensive in terms of processing time.
Private Sub BgWorker_ProgressChanged()Sub BgWorker_ProgressChanged(ByVal sender As Object, _
ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
Handles BgWorker.ProgressChanged
' Reject a nested call.
If CallInProgress Then Return
CallInProgress = True
' Display the message received in the UserState property
lblMessage.Text = e.UserState.ToString()
' Display all files added since last call.
For idx As Integer = lstFiles.Items.Count To Files.Count - 1
lstFiles.Items.Add(Files(idx))
Next
' If a Me.Refresh is in this code you will need to place a Application.DoEvents()
' otherwise the UI will not respond without them it works fine.
' Me.Refresh()
' Let the Windows OS process messages in the queue
' Application.DoEvents()
CallInProgress = False
End Sub
' The background thread calls this event just before it reaches the End Sub
' of the DoWork event. It is OK to access user controls in the UI from this event.
Private Sub BgWorker_RunWorkerCompleted()Sub BgWorker_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BgWorker.RunWorkerCompleted
' Display the last message and reset the Start/Stop button text
lblMessage.Text = e.Result.ToString()
btnStart.Text = "Start"
End Sub
End Class
在win2k+vb.net 2005 测试过。不错。
This code sample assumes that the form has the following controls on it:( 需要的控件:)
TextBox called txtSearchPath
TextBox called txtSearchPattern
Label called lblMessage
Button called btnStart 注意这个按钮的.text属性为:“Start”
ListBox called lstFiles
Imports System.IO
Public Class SearchFilesFrmClass SearchFilesFrm
' To set up for a background operation, add an event handler for the DoWork event.
' Call your time-consuming operation in this event handler. To start the operation,
' call RunWorkerAsync. To receive notifications of progress updates, handle the
' ProgressChanged event. To receive a notification when the operation is completed,
' handle the RunWorkerCompleted event.
' Note
' You must be careful not to manipulate any user-interface objects in your DoWork
' event handler. Instead, communicate to the user interface through the
' ProgressChanged and RunWorkerCompleted events.
' If your background operation requires a parameter, call RunWorkerAsync with your
' parameter. Inside the DoWork event handler, you can extract the parameter from
' the DoWorkEventArgs.Argument property.
' Store the results of the search
Private Files As List(Of String)
' Used to prevent nested calls to ProgressChanged
Private CallInProgress As Boolean
' The Worker thread
Private WithEvents BgWorker As New System.ComponentModel.BackgroundWorker
Private Sub SearchFilesFrm_Load()Sub SearchFilesFrm_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
' Enable ProgressChanged and Cancellation mothed
BgWorker.WorkerReportsProgress = True
BgWorker.WorkerSupportsCancellation = True
End Sub
' Start and Stop the search
Private Sub btnStart_Click()Sub btnStart_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnStart.Click
If btnStart.Text = "Start" Then
If Not Directory.Exists(txtSearchPath.Text.Trim()) Then
MessageBox.Show("The Search Directory does not exist", _
"Path Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
If txtSearchPattern.Text.Trim() = "" Then txtSearchPattern.Text = "*"
Dim arguments() As String = {txtSearchPath.Text.Trim(), _
txtSearchPattern.Text.Trim()}
lstFiles.Items.Clear()
' Start the background worker thread. Thread runs in DoWork event.
BgWorker.RunWorkerAsync(arguments)
btnStart.Text = "Stop"
Else
BgWorker.CancelAsync()
End If
End Sub
' Start the Asynchronous file search. The background thread does it work from
' this event.
Private Sub BgWorker_DoWork()Sub BgWorker_DoWork(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BgWorker.DoWork
'Retrieve the search path which was requested
Dim path As String = DirectCast(e.Argument, String())(0)
Dim pattern As String = DirectCast(e.Argument, String())(1)
' Invoke the worker procedure
Files = New List(Of String)
SearchFiles(path, pattern)
' Return a result to the RunWorkerCompleted event
Dim message As String = String.Format("Found {0} Files", Files.Count)
e.Result = message
End Sub
' Recursively search directory and sub directories
Private Sub SearchFiles()Sub SearchFiles(ByVal path As String, ByVal pattern As String)
' Displat message
Dim message As String = String.Format("Parsing Directory {0}", path)
BgWorker.ReportProgress(0, message)
'Read the files and if the Stop button is pressed cancel the operation
For Each fileName As String In Directory.GetFiles(path, pattern)
If BgWorker.CancellationPending Then Return
Files.Add(fileName)
Next
For Each dirName As String In Directory.GetDirectories(path)
If BgWorker.CancellationPending Then Return
SearchFiles(dirName, pattern)
Next
End Sub
' The bacground thread calls this event when you make a call to ReportProgress
' It is OK to access user controls in the UI from this event.
' If you use a Progress Bar or some other control to report the tasks progress
' you should avoid unnecessary calls to ReportProgress method because this causes
' a thread switch which is a relatively expensive in terms of processing time.
Private Sub BgWorker_ProgressChanged()Sub BgWorker_ProgressChanged(ByVal sender As Object, _
ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
Handles BgWorker.ProgressChanged
' Reject a nested call.
If CallInProgress Then Return
CallInProgress = True
' Display the message received in the UserState property
lblMessage.Text = e.UserState.ToString()
' Display all files added since last call.
For idx As Integer = lstFiles.Items.Count To Files.Count - 1
lstFiles.Items.Add(Files(idx))
Next
' If a Me.Refresh is in this code you will need to place a Application.DoEvents()
' otherwise the UI will not respond without them it works fine.
' Me.Refresh()
' Let the Windows OS process messages in the queue
' Application.DoEvents()
CallInProgress = False
End Sub
' The background thread calls this event just before it reaches the End Sub
' of the DoWork event. It is OK to access user controls in the UI from this event.
Private Sub BgWorker_RunWorkerCompleted()Sub BgWorker_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BgWorker.RunWorkerCompleted
' Display the last message and reset the Start/Stop button text
lblMessage.Text = e.Result.ToString()
btnStart.Text = "Start"
End Sub
End Class
在win2k+vb.net 2005 测试过。不错。
相关文章推荐
- 【zt】一个用 Observer 模式实现的 Thread 线程文件搜索例子
- svn 单独导出某一个目录文件
- 一个emacs扩展,从指定目录或文件中搜索指定关键字
- Java读取一个目录(文件夹)下的文件例子
- 关于文件目录线程级深度优先搜索效率的研究
- 搜索一个目录下名字中有key的目录和文件
- 大数据学习35:一个scala 操控 HDFS 文件目录的小例子
- 搜索和替换文件或目录的一个好类--很实用
- C#遍历某目录及其子目录下所有文件的一个例子
- 搜索和替换文件或目录的一个好类--很实用
- Go 1.5关键字搜索目录、文件、文件内容_修复一个小BUG
- 搜索和替换文件或目录的一个好类--很实用
- CoreJava_线程并发(堵塞队列):在某个目录下搜索含有某keyword的文件
- 一个遍历指定目录下所有文件的例子
- 采用多线程和生产者消费者模式来实现对于一个目录以及所有子目录下的文件内容的搜索,打印出包含指定关键字的行.
- Windows 窗体编程 如何:使用后台线程搜索文件 (线程经典例子)
- 一个文件搜索(使用正则)的例子
- hadoop入门例子(一)-输出hdfs上面的某一个目录下面的文件
- 自己写的一个将指定目录下的文本文件集合成单独的一个大文本文件工具
- 查找该目录下指定文件类型的用 vc 6.0 编写 的关于文件搜索的例子