반응형

* 객체 직렬화 (Serialization)

 - 객체를 메모리나 파일, 데이터 베이스 등 에 저장할 때 쓰이는 방식

 

* 예제

 

메인 화면

Form1.vb

 

Imports System.Runtime.Serialization
Imports System.Collections

Public Class Form1
    Dim TT As T_TEST
    Dim t As clsTEST = New clsTEST

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TT.strTEST = "객체 직렬화"
        t.FnTest = 15430305

        Using stm As System.IO.Stream = System.IO.File.Open("ect.class", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            '객체 직렬화 저장...
            bf.Serialize(stm, t)
            stm.Close()
        End Using
        TextBox1.Text += "Object Class" + vbCrLf
        TextBox1.Text += "lTest Value : " + t.FnTest.ToString() + vbCrLf
        TextBox1.Text += "객체 클래스 저장 완료..." + vbCrLf + vbCrLf


        Using stm As System.IO.Stream = System.IO.File.Open("ect.struct", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            '객체 직렬화 저장...
            bf.Serialize(stm, TT)
            stm.Close()
        End Using

        TextBox1.Text += "Object Struct" + vbCrLf
        TextBox1.Text += "sText Value : " + TT.strTEST + vbCrLf
        TextBox1.Text += "객체 구조체 저장 완료..." + vbCrLf

        TextBox1.Text += "=========================" + vbCrLf

    End Sub

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

        Using stm As System.IO.Stream = System.IO.File.Open("ect.class", System.IO.FileMode.Open, System.IO.FileAccess.Read)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            '역직렬화 후 객체 클래스로 형변환...
            Dim a As clsTEST = CType(bf.Deserialize(stm), clsTEST)
            stm.Close()

            TextBox1.Text += "Object Class" + vbCrLf
            TextBox1.Text += "lTest Value : " + a.FnTest().ToString() + vbCrLf
            TextBox1.Text += "객체 클래스 불러오기 완료..." + vbCrLf + vbCrLf

        End Using


        Using stm As System.IO.Stream = System.IO.File.Open("ect.struct", System.IO.FileMode.Open, System.IO.FileAccess.Read)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            '역직렬화 후 객체 구조체로 형 변환...
            Dim a As T_TEST = CType(bf.Deserialize(stm), T_TEST)
            stm.Close()

            TextBox1.Text += "Object Struct" + vbCrLf
            TextBox1.Text += "sText Value : " + a.strTEST + vbCrLf
            TextBox1.Text += "객체 구조체 불러오기 완료..." + vbCrLf

        End Using
    End Sub
End Class


<Serializable()> Public Structure T_TEST
    Public strTEST As String
End Structure


<Serializable()> Public Class clsTEST
    Dim lTest As Long

    Public Sub New()
        lTest = 5
    End Sub

    Property FnTest() As Integer
        Get
            Return lTest
        End Get
        Set(ByVal value As Integer)
            lTest = value
        End Set
    End Property

    Public Function Test() As Long
        Return lTest
    End Function


End Class

* 객체 직렬화를 위해서는 그 선언 객체에 반드시 <Serializable()> 을 붙여 줘야 됨.

 

 

[C#] ▼

https://kdsoft-zeros.tistory.com/26

 

[C#] 객체 파일 저장 및 불러오기 예제 (Serialization)

* 객체 직렬화 (Serialization) - 객체를 메모리나 파일 , 데이터베이스에 저장할 때 쓰이는 방식 * 예제 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System..

kdsoft-zeros.tistory.com

 

반응형
반응형

BackgroundWorker 클래스를 사용 하면 별도 전용 스레드에서 작업을 실행할 수 있습니다. 다운로드 및 데이터베이스 트랜잭션과 같은 시간이 많이 걸리는 작업은 사용자 인터페이스 (UI) 실행 하 고 응답을 멈춘 것 처럼 보일 수 발생할 수 있습니다. 이러한 작업으로 인 한 지연이 길어지는 경우 및 응답성이 뛰어난 UI를 구성할 때의 BackgroundWorker 클래스는 편리 하 게 솔루션을 제공 합니다.

시간이 많이 걸리는 작업을 백그라운드에서를 실행 하려면 만들기를 BackgroundWorker 작업이 완료 되 면 신호 확인 하 고 작업의 진행률을 보고 하는 이벤트를 수신 합니다. 만들 수 있습니다는 BackgroundWorker 프로그래밍 방식으로에서 폼으로 끌어 놓을 수 있습니다 합니다 구성 요소 탭의 도구 상자. 만드는 경우는 BackgroundWorker Windows Forms 디자이너에서 구성 요소 트레이에 표시 됩니다 하 고 해당 속성이 속성 창에 표시 됩니다.

백그라운드 작업에 대 한 설정에 대 한 이벤트 처리기를 추가 합니다 DoWork 이벤트입니다. 이 이벤트 처리기에서 시간이 오래 걸리는 작업을 호출 합니다. 작업을 시작 하려면 호출 RunWorkerAsync합니다. 진행률 업데이트의 알림을 받으려면 처리는 ProgressChanged 이벤트입니다. 작업이 완료 될 때 알림을 받으려면 처리는 RunWorkerCompleted 이벤트입니다.

 

Background Worker 속성

BackgroundWorker 이벤트

 

예제

다음 코드 예제는 기본 사항을 보여줍니다는 BackgroundWorker 시간이 많이 걸리는 작업을 비동기적으로 실행 하기 위한 클래스입니다. 다음 그림에서는 출력의 예를 보여 줍니다.

 

이 코드를 실행 하려면 Windows Forms 애플리케이션을 작성 합니다. 추가 Label 라는 컨트롤 resultLabel 두 개의 추가 Button 컨트롤 이라는 startAsyncButton  cancelAsyncButton합니다. 만들 Click 두 단추에 대 한 이벤트 처리기입니다. 구성 요소 탭 도구 상자의 추가 BackgroundWorker 라는 구성 요소 backgroundWorker1합니다. 만들 DoWork, ProgressChanged, 및 RunWorkerCompleted 에 대 한 이벤트 처리기는 BackgroundWorker합니다. 폼의 코드에서 기존 코드를 다음 코드로 바꿉니다.

 

 

Imports System.Windows.Forms

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        BackgroundWorker1.WorkerReportsProgress = True
        BackgroundWorker1.WorkerSupportsCancellation = True
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If BackgroundWorker1.IsBusy <> True Then
            ' 백그라운드 스레드 시작
            BackgroundWorker1.RunWorkerAsync()
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If BackgroundWorker1.WorkerSupportsCancellation = True Then
            ' 백그라운드 스레드 취소
            BackgroundWorker1.CancelAsync()
        End If
    End Sub

    '스레드 동작 구문
    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim worker As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)
        Dim i As Integer
        For i = 1 To 10 Step i + 1
            If worker.CancellationPending = True Then
                e.Cancel = True
                Exit For
            Else
                ' Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(500)
                worker.ReportProgress(i * 10)
            End If
        Next
    End Sub

    '라벨 디스플레이 업데이트
    Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        resultLabel.Text = (e.ProgressPercentage.ToString() + "%")
    End Sub

    '백그라운드 워커 컨트롤 상태 표시
    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled = True Then
            resultLabel.Text = "Canceled!"
        ElseIf Not e.Error Is Nothing Then
            resultLabel.Text = "Error: " + e.Error.Message
        Else
            resultLabel.Text = "Done!"
        End If
    End Sub
End Class

 

*참고 : https://docs.microsoft.com/ko-kr/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.8

 

[C#] 백그라운드 스레드(BackGround Worker Class)

 

[C#] 백그라운드 스레드(BackGround Worker Class)

BackgroundWorker 클래스를 사용 하면 별도 전용 스레드에서 작업을 실행할 수 있습니다. 다운로드 및 데이터베이스 트랜잭션과 같은 시간이 많이 걸리는 작업은 사용자 인터페이스 (UI) 실행 하 고 응답을 멈춘..

kdsoft-zeros.tistory.com

 

반응형
반응형

* 크로스 스레드

 - 자신의 스레드가 아닌 다른 스레드가 그 컨트롤에 접근 했을 때 나는 오류 

 

 

*해결 방법 예제

 

 

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.Object, ByVal 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.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
		
        If (thMain Is Nothing) Then

            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.Object, ByVal 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.Object, ByVal 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번째 방법 으로 예제를 만들어 보았습니다.

 

*요약

 

[VBNET] 델리 게이트 (Delegate) - 델리게이트란? , 선언 방법과 간단한 예제

 

[VBNET] 델리 게이트 (Delegate) - 델리게이트란? , 선언 방법과 간단한 예제

*델리 게이트(Delegate) - 대리자 로써 C 언어나 C++ 언어 를 공부한 사람이라면 쉽게 접할 수 있는 함수 포인터와 비슷한 기능을 합니다. 또한 콜백 함수 기능 역할도 수행 *델리 게이트 선언 방법과 간단한 예제..

kdsoft-zeros.tistory.com

[C#] 크로스 스레드 (Cross Thread) 예제

 

[C#] 크로스 스레드 (Cross Thread) 예제

* 크로스 스레드 - 자신의 스레드가 아닌 다른 스레드가 그 컨트롤에 접근했었을 때 발생하는 오류 * 해결 방법 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using..

kdsoft-zeros.tistory.com

 

반응형
반응형

*델리 게이트(Delegate)

 - 대리자 로써 C 언어나 C++ 언어 를 공부한 사람이라면 쉽게 접할 수 있는 함수 포인터와

   비슷한 기능을 합니다.  또한 콜백 함수 기능 역할도 수행 

   

*델리 게이트 선언 방법과 간단한 예제

 

Public Class Form1

    '델리 게이트 선언...
    Delegate Function delegateFuncA(ByVal a As Integer, ByVal b As Integer) As Integer
    Delegate Sub delegateFuncB(ByVal a As Integer, ByVal b As Integer)
    Delegate Function delegateFuncC(ByVal a As Integer) As String


    '폼 버튼 이벤트...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'FuncA 함수에 대한 델리게이트 초기화
        Dim dfa As delegateFuncA = New delegateFuncA(AddressOf FuncA)
        MessageBox.Show(dfa(5, 6).ToString() + " , Delegate 함수 사용")

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'FuncB 함수에 대한 델리게이트 초기화
        Dim dfa As delegateFuncB = New delegateFuncB(AddressOf FuncB)
        dfa(5, 6)
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        'FuncC 함수에 대한 델리게이트 초기화
        Dim dfa As delegateFuncC = New delegateFuncC(AddressOf FuncC)
        MessageBox.Show(dfa(5))
    End Sub

    '폼 내부 함수들...
    Private Function FuncA(ByVal a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function

    Private Sub FuncB(ByVal a As Integer, ByVal b As Integer)
        MessageBox.Show((a + b).ToString())
    End Sub

    Private Function FuncC(ByVal a As Integer) As String
        Return (a + 15).ToString()
    End Function

End Class

위 코드와 같이 델리 게이트 선언 형식과 함수 형식이 같으며,

(델리게이트 함수 이름은 변수 이름(delegateFuncA,B,C) 사용자 마음대로 지정 가능)

만약 리턴 형식 및 전달 인자 형식이 틀리게 되면 아래의 그림과 같이 오류가 발생 하게 됩니다.

 

간략히 델리 게이트가 무엇이며, 간단한 예제를 만들어 봤습니다.

 

* C# 델리 게이트 (Delegate) -  1 델리게이트란? , 선언 방법과 간단한 예제

https://kdsoft-zeros.tistory.com/18

반응형
반응형

#Region "프로젝트 폼 목록 읽어 오기..."


    '프로젝트 내 폼 찾기...
    Public Shared Function GetAssemblyForm(ByVal strFormName As String) As Form
        Dim f As Form = Nothing

        For Each t As Type In System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
            If (t.Name = strFormName) Then                       '찾을려는 폼 이름과 같으면....
                Dim o As Object = Activator.CreateInstance(t)   '새로운 인스턴스 개체 생성...
                f = CType(o, Form)                                     '개체를 Form 개체로 변환...
                Exit For
            End If
        Next

        Return f                                                           '찾았는 폼 개체 반환 Nothing 이면 못찾음 아니면 찾음
    End Function


  '프로젝트 내 폼 리스트 반환...
    Public Shared Function GetAssemblyFormList() As List(Of Form)
        Dim ltForm As List(Of Form) = New List(Of Form)

        For Each t As Type In System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
            If (t.BaseType.FullName.ToString() = "System.Windows.Forms.Form") Then ' 개체 타입이 Form 이면...
                Dim o As Object = Activator.CreateInstance(t)       '새로운 인스턴스 개체 생성...
                Dim f As Form = CType(o, Form)                       '개체를 Form 개체로 변환...
                ltForm.Add(f)                                                '리스트변수에 찾은 Form 개체 담기...
            End If
        Next

        Return ltForm                                                       '폼 리스트 반환...
    End Function

#End Region

 

 

Public Class Form1

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

        Dim ltList As List(Of Form) = GetAssemblyFormList()

        For iCount As Integer = 0 To ltList.Count - 1

            Dim f As Form = CType(ltList(iCount), Form)
            ListBox1.Items.Add(f.Text)

        Next


    End Sub

    Public Shared Function GetAssemblyForm(ByVal strFormName As String) As Form
        Dim f As Form = Nothing

        For Each t As Type In System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
            If (t.Name = strFormName) Then
                Dim o As Object = Activator.CreateInstance(t)
                f = CType(o, Form)
                Exit For
            End If
        Next

        Return f
    End Function

    Public Shared Function GetAssemblyFormList() As List(Of Form)
        Dim ltForm As List(Of Form) = New List(Of Form)

        For Each t As Type In System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
            If (t.BaseType.FullName.ToString() = "System.Windows.Forms.Form") Then
                Dim o As Object = Activator.CreateInstance(t)
                Dim f As Form = CType(o, Form)
                ltForm.Add(f)
            End If
        Next

        Return ltForm
    End Function


End Class
반응형
반응형

VB6 처럼 VBNET 도 컨트롤 배열처럼 사용 하기

VB6 은 컨트롤 배열작성시 인덱스 가 정수형으로 사용 

Label(1) Label(2) Label(3) Label(4) Label(5) Label(6)~

 

for iCount to 6

     Label(iCount).Text =""

Next

 

하지만 아래와 같이 VBNET 은 문자 123456 ~ 로  컨트롤 이름으로

찾아서 사용

 

--선언 방법

아래의 Public 모듈을 전역 클래스나 모듈에 선언 

 

Public Module ControlSelectorExtension
    <System.Runtime.CompilerServices.Extension()> Public Function FindByName(Of T)(ByVal targetClass As Object, ByVal name As String) As T
        Dim info As Reflection.PropertyInfo = targetClass.GetType().GetProperty(name, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
        Return DirectCast(info.GetValue(targetClass, Nothing), T)
    End Function
    <System.Runtime.CompilerServices.Extension()> Public Function FindByName(Of T)(ByVal name As String, ByVal targetClass As Object) As T
        Dim info As Reflection.PropertyInfo = targetClass.GetType().GetProperty(name, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
        Return DirectCast(info.GetValue(targetClass, Nothing), T)
    End Function
End Module

 

 

-- 사용 예제 및 방법 

 

Private Sub Control_Init()

        For iCount As Integer = 1 To 10
            FindByName(Of Label)("lbl" + iCount.ToString()).Text = ""
            FindByName(Of Label)("lbl" + iCount.ToString() + "_" + iCount.ToString()).Text = ""
            FindByName(Of Label)("lblWorkingTime" + iCount.ToString()).Text = ""
        Next

End Sub

 

* Panel.Controls 나 Form.Controls 로 찾는 방식이랑은 틀림

ex) Panel1 에 Label 1,2,3,4,5 가 있고 Pannel2 에 Label 6,7,8,9 가 있음

   Panel1.Controls 로 Label12345 를 찾고 Panel2.Controls 로 6789 를 찾아야 됨.

 

반응형
반응형

Public Function After_Time(ByVal NowTime As Date, ByVal BeforeTime As Date) As Double

        Dim ts As TimeSpan = NowTime - BeforeTime

        Return ts.TotalSeconds

    End Function

 

반환 되는 값 1 은 1초 이며 0.5 초 500 미리

반응형

+ Recent posts