Imports System.ComponentModel Imports System.Threading Imports System.Threading.Tasks Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Button1.Text = "元の実装" Button2.Text = "Aync/Await版" Button3.Text = "BackgrouneWorker版" BackgroundWorker1.WorkerReportsProgress = True ResetProgressBar() End Sub Private Sub ResetProgressBar(Optional min As Integer = 0, Optional max As Integer = 100, Optional current As Integer = 0) ProgressBar1.Minimum = min ProgressBar1.Maximum = max ProgressBar1.Value = current End Sub '長い処理を同期的に実行するメソッド Private Sub LongTimeAction() Thread.Sleep(1000) Debug.WriteLine(Now.Ticks) End Sub '長い処理を非同期的に実行するメソッド Private Function LongTimeActionAsync() As Task Return Task.Run(Sub() Thread.Sleep(1000) Debug.WriteLine(Now.Ticks) End Sub) End Function Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ResetProgressBar() For i = 0 To 100 LongTimeAction() ProgressBar1.Value = i Next MsgBox("終了") End Sub Private Async Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ResetProgressBar() For i = 0 To 100 Await LongTimeActionAsync() ProgressBar1.Value = i Next MsgBox("終了") End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click BackgroundWorker1.RunWorkerAsync() End Sub Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork Dim bgw = DirectCast(sender, BackgroundWorker) For i = 0 To 100 LongTimeAction() bgw.ReportProgress(i) Next e.Result = "終了" End Sub Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged ProgressBar1.Value = e.ProgressPercentage End Sub Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted MsgBox(e.Result) End Sub End Class