⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frmbackgroundworkerusage.vb

📁 Microsoft Mobile Development Handbook的代码,有C#,VB,C++的
💻 VB
字号:
Imports Microsoft.VisualBasic
Imports System
Imports System.ComponentModel
Imports System.Windows.Forms

Namespace CodeForChapter11cs
  Public Partial Class frmBackgroundWorkerUsage
	  Inherits Form
	Public Sub New()
	  InitializeComponent()
	End Sub

	Private bw As BackgroundWorker

	' cancel
	Private Sub menuItem2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles menuItem2.Click
	  If Not bw Is Nothing Then
		bw.CancelAsync()
	  End If
	End Sub

	' start
	Private Sub menuItem1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles menuItem1.Click
	  menuItem1.Enabled = False
	  textBox1.Enabled = False
	  label2.Text = "will kick it off"

	  bw = New BackgroundWorker(Me)
	  bw.WorkerReportsProgress = True
	  bw.WorkerSupportsCancellation = True

	  AddHandler bw.DoWork, AddressOf bw_DoWork
	  AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
	  AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

	  Dim someState As Object = textBox1.Text
	  bw.RunWorkerAsync(someState)
	End Sub

	Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
	  ' can touch UI. Thread communicates to UI. We don't have to Control.Invoke explicitly.
	  Dim computationResult As Object = e.Result
	  label2.Text = computationResult.ToString()

	  menuItem1.Enabled = True
	  textBox1.Enabled = True
	End Sub

	Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
	  ' worker reports progress. Again we can touch UI. Marshalling done for us
	  label1.Text = e.UserState.ToString()
	End Sub

	Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
	  ' This is in worker thread. CAnnot touch UI from here
	  Dim b As BackgroundWorker = CType(sender, BackgroundWorker)

	  Dim stillMoreWorkToDo As Boolean = True ' this somehow changes to false in real scenario
	  Dim progress As Integer = 0
	  Do While stillMoreWorkToDo
		' optionally finish if user requested cancellation
		If b.CancellationPending Then
		  e.Cancel = True
		  e.Result = "cancelled " & e.Argument.ToString() ' could assign any other object
		  Return
		End If

		' do time consuming work
		System.Threading.Thread.Sleep(2000)

		' optionally report progress
		progress += 1 ' real world calculates this
		Dim someOtherProgressVar As Object = New Random().Next()
		b.ReportProgress(progress, someOtherProgressVar)

		' somehow determine job is done
		If progress = 5 Then
		stillMoreWorkToDo = False
		End If
	  Loop

	  e.Result = "finished :) " & e.Argument.ToString() ' could assign any other object
	End Sub
  End Class
End Namespace

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -