[VBNET] 크로스 스레드 (Cross Thread) 예제 > vb.net

본문 바로가기

vb.net

[Controls] [VBNET] 크로스 스레드 (Cross Thread) 예제

회원사진
하나를하더라도최선을
2021-05-02 11:22 4,405 0

본문



'// Example 컨트롤 삽입
 
Dim DL As New DGV_LIST
If CType(Me.Panel10.Controls("RP"), DGV_LIST).GroupBox1.InvokeRequired = True Then
    CType(Me.Panel10.Controls("RP"), DGV_LIST).GroupBox1.Invoke(CType(Function()
                    CType(Me.Panel10.Controls("RP"), DGV_LIST).GroupBox1.Controls.Add(DL)
                End Function, MethodInvoker))
Else
    CType(Me.Panel10.Controls("RP"), DGV_LIST).GroupBox1.Controls.Add(DL)
End If
 
 
 
 
'// Example 01
Private Sub Display()
    If Me.InvokeRequired Then
        Me.Invoke(Sub() Received.AppendText(" - " & RXArray))
        Return
    End IF
End Sub
 
 
* 크로스 스레드
 - 자신의 스레드가 아닌 다른 스레드가 그 컨트롤에 접근 했을 때 나는 오류 
 
*해결 방법 예제
 
Form1.vb
 
 
 
Public Class Form1
 
    '   스레드의 동작을 제어하는 메서드 
    '   Abort():강제 종료 
    '   Interrupt():대기 중인 스레드를 중단 
    '   Join(): 스레드가 종료될 때까지 호출 스레드를 차단 
    '   Sleep(int millisecondsTimeout): 지정된 시간(밀리초)동안 스레드를 중지 
    '   Start(): 스레드 시작 
    '   Suspend(): 일시 중지 
    '   Resume(): 일시 중지된 스레드 수행 
 
    Dim thMain As Threading.Thread
    Dim bThread As Boolean = False
 
    '최초 한번만 실행...
    Dim bThreadStart As Boolean = False
 
#Region "2번째 방법..."
    '델리게이트 선언...
    Delegate Sub TextBoxDelegate(ByVal strText As String)
    '델리게이트를 위한 함수 선언...
    Private Sub TextBoxFunc(ByVal strText As String)
        txtThread.Text = strText
    End Sub
 
#End Region
 
    Private Sub Form1_Load(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles MyBase.Load
 
        '1번째 해결 방법...
        'CheckForIllegalCrossThreadCalls = False
 
        thMain = New Threading.Thread(New Threading.ThreadStart(AddressOf Thread_Timer))
 
        '스레드를 백그라운드로 지정...
        '기본 : 포어그라운드 차이점 => 프로그램 종료시 백그라운드 스레드는 하던일 멈추고 같이 종료...
        '포어그라운드 스레드는 하던일 다 하고 나면 종료...
        thMain.IsBackground = True
        
    End Sub
 
    Private Sub Form1_FormClosed(ByVal sender As System.ObjectByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        
        If (thMain Is NothingThen
 
            If (bThreadStart) Then
                thMain.Abort()        '스레드 강제 종료...
            Else
                thMain.Interrupt()    '대기중인 스레드 종료...
            End If
            '스레드 변수에 nothing 대입으로 사용을 안하겠다 표시
            thMain = Nothing
        End If
 
    End Sub
 
    Private Sub button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles button1.Click
 
        If (Not bThreadStart) Then   '프로그램 실행시 한번도 스레드가 실행 되지 않았음으로 최초 한번 실행...
            bThread = True
            bThreadStart = True
            thMain.Start()                     '스레드 시작
        Else   '일시 정지일 경우 다시 실행...
            bThread = True
            thMain.Resume()                    '일시 정지된 스레드 다시 시작
        End If
 
    End Sub
 
    Private Sub button2_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles button2.Click
        bThread = False
        thMain.Suspend()                       '스레드 일시 정지...
    End Sub
 
 
    Sub Thread_Timer()
 
        While (bThread)
 
            '크로스 스레드 오류 내기...
            'txtThread.Text = "크로스 스레드 예제..."
 
            '2번째 방법 사용
            Me.Invoke(New TextBoxDelegate(AddressOf TextBoxFunc), "크로스 스레드 예제...")
 
            Threading.Thread.Sleep(1000)
 
        End While
 
    End Sub
 
    
End Class
위 소스 예제를 보시는 바와 같이 1,2번째 방법 으로 예제를 만들어 보았습니다.
 
 
 
*요약
 
 
 
 
 
 
출처: https://kdsoft-zeros.tistory.com/23?category=846222 [삽질하는 개발자...]
 

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색