VB.NET覚書

VB.NETの覚書
[個人メモ] [仕事メモ] [アイデア] [Ruby]
[TIPS] [対応表] [コメント書き方] [.NET Tips] [VB中学校] [VB.NET の入門サイト] [VB.NET コーディング標準 ] [VBレスキュー] [NonSoft]

2017-05-22

backgroundwarker バックグランド処理

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If BackgroundWorker1.IsBusy = True Then
            MsgBox("動作中")
            Return
        End If

        BackgroundWorker1.WorkerSupportsCancellation = True
        BackgroundWorker1.WorkerReportsProgress = True
        BackgroundWorker1.RunWorkerAsync(Integer.Parse(TextBox1.Text))
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        
        Dim start As Integer = CInt(e.Argument)

        If start < 1 Or start > 100 Then
            start = 1
        End If

        For i As Integer = start To 100
            If Me.BackgroundWorker1.CancellationPending = True Then
                e.Cancel = True
                Return
            End If

            System.Threading.Thread.Sleep(100)
            BackgroundWorker1.ReportProgress(i)
        Next
        e.Result = "終了"
    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        ProgressBar1.Value = e.ProgressPercentage
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        BackgroundWorker1.CancelAsync()
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled Then
            MsgBox("cancel")
        Else
            MsgBox(e.Result.ToString)
        End If
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class


BackGrowndWorkerをクラス

以下のサイトを参考にしました。

https://msdn.microsoft.com/ja-jp/library/cc221403(v=vs.95).aspx

Imports System.ComponentModel

Public Class ClsBackGround

    ''' <summary>
    ''' backgroundWorker
    ''' </summary>
    Private m_backGroundWorker As BackgroundWorker

    ''' <summary>
    ''' 進捗状況
    ''' </summary>
    Public Property progress As Integer

    ''' <summary>
    ''' 出力
    ''' </summary>
    Public Property result As String

    ''' <summary>
    ''' 終了状態
    ''' </summary>
    Public Property resultStatus As String

    ''' <summary>
    ''' 作業終了
    ''' </summary>
    Public Event Complete As EventHandler

    ''' <summary>
    ''' 進捗
    ''' </summary>
    Public Event ProgressChange As EventHandler

    ''' <summary>
    ''' 作業内容
    ''' </summary>
    Public Event DoWork As EventHandler
    Public Const ST_DONE = "Done!"
    Public Const ST_ERROR = "Error:"
    Public Const ST_CANCEL = "Canceled!"


    Sub New()
        m_backGroundWorker = New BackgroundWorker

        AddHandler m_backGroundWorker.DoWork, AddressOf m_backGroundWorker_DoWork
        AddHandler m_backGroundWorker.ProgressChanged, AddressOf m_backGroundWorker_ProgressChanged
        AddHandler m_backGroundWorker.RunWorkerCompleted, AddressOf m_backGroundWorker_RunWorkerCompleted

    End Sub

    Public Function start(Optional ByRef value As String = "") As Boolean

        If Not m_backGroundWorker.IsBusy Then
            resultStatus = ""
            m_backGroundWorker.WorkerSupportsCancellation = True
            m_backGroundWorker.WorkerReportsProgress = True
            m_backGroundWorker.RunWorkerAsync(value)
            Return True
        Else
            Return False
        End If

    End Function

    Public Sub cancel()

        m_backGroundWorker.CancelAsync()

    End Sub

    Public Function isBusy() As Boolean

        Return m_backGroundWorker.IsBusy

    End Function

    Private Sub m_backGroundWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)

        RaiseEvent DoWork(sender, e)

    End Sub

    Private Sub m_backGroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)

        progress = e.ProgressPercentage
        RaiseEvent ProgressChange(sender, e)

    End Sub

    Private Sub m_backGroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)

        result = ""

        If e.Cancelled = True Then
            resultStatus = ST_CANCEL
        ElseIf e.Error IsNot Nothing Then
            resultStatus = ST_ERROR & e.Error.Message
        Else
            resultStatus = ST_DONE
            result = e.Result
        End If

        RaiseEvent Complete(sender, e)

    End Sub

    Public Sub setProgress(value As Integer, ByRef sender As Object)

        Dim worker As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)

        If 0 <= value And 100 >= value Then
            worker.ReportProgress(value)
        End If

    End Sub


    Public Function isCancel(ByRef sender As Object, ByRef e As System.ComponentModel.DoWorkEventArgs) As Boolean

        Dim Ret As Boolean = False

        Dim worker As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)

        If worker.CancellationPending = True Then
            e.Cancel = True
            Ret = True
        Else
            Ret = False
        End If

        Return Ret

    End Function

    Public Function getArgment(e As System.ComponentModel.DoWorkEventArgs) As String
        Return e.Argument
    End Function

    Public Sub setResult(res As String, e As System.ComponentModel.DoWorkEventArgs)
        e.Result = res
    End Sub


End Class



Public Class Form1

    Dim WithEvents bw As ClsBackGround


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        bw.start("5")

    End Sub


    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        bw = New ClsBackGround

    End Sub

    Private Sub bw_Complete(sender As Object, e As System.EventArgs) Handles bw.Complete

        MsgBox(bw.resultStatus & " " & bw.result)

    End Sub

    Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork

        Dim start As Integer = Integer.Parse(bw.getArgment(e))

        For i = start To 10
            If bw.isCancel(sender, e) = True Then
                Exit For
            Else
                System.Threading.Thread.Sleep(500)
                bw.setProgress(i * 10, sender)
            End If
        Next

        bw.setResult("END", e)

    End Sub

    Private Sub bw_ProgressChange(sender As Object, e As System.EventArgs) Handles bw.ProgressChange

        Me.ProgressBar1.Value = bw.progress

    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

        bw.cancel()

    End Sub
End Class

Process サンプル

参考にしたサイト

http://www.atmarkit.co.jp/fdotnet/chushin/introwinform_05/introwinform_05_02.html

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Me.Process1.StartInfo.FileName = "notepad.exe"
        Me.Process1.Start()
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Me.Process1.WaitForExit()
        MessageBox.Show( _
          Me.Process1.StartInfo.FileName & " 終了", _
          Me.Text, _
          MessageBoxButtons.OK)
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        Me.Process1.Kill()
    End Sub
End Class

EventLogサンプル

参考にしたサイト

http://www.atmarkit.co.jp/fdotnet/chushin/introwinform_05/introwinform_05_02.html

Public Class Form1
    Private Sub Button1_Click( _
    ByVal sender As Object, ByVal e As EventArgs) _
        Handles Button1.Click
        If Me.TextBox1.Text.Length > 0 Then
            Me.EventLog1.Source = "Application"
            Me.EventLog1.WriteEntry(Me.TextBox1.Text)
        End If
    End Sub

    Private Sub Button2_Click( _
        ByVal sender As Object, ByVal e As EventArgs) _
            Handles Button2.Click
        If Me.TextBox1.Text.Length > 0 Then
            EventLog.WriteEntry("Application", _
                                Me.TextBox1.Text, _
                                EventLogEntryType.Warning)
        End If
    End Sub
End Class
トラックバック - http://sub.g.hatena.ne.jp/garyo/20170522