BackgroundWorker 컨트롤을 이용해서 실시간 차트를 그려보자.



히포차트를 통해 다양한 실시간 차트를 그리는 방법을 알아보고 있습니다. 이번에는 닷넷 컨트롤인 BackgroundWorker 를 이용해서 그리는 방법을 알아보겠습니다. BackgroundWorker 는 스레딩 프로그램을 손쉽게 구현할 수 있게 해주는 컨트롤입니다.

[적용 버전]
  베타 2.0 이상

 [시나리오]
 
 1. 백그라인트워커를 통해 1초마다 들어오는 데이터를 히포차트에 넘겨 실시간으로 그려주되 x축은 총 20개를 유지하도록 한다.
 2. 라인차트로 그리고 포인트 크기는 4으로 하고 포인트가 Fill되는 모양으로 한다.
 3. x축은 분 : 초 형식(00:00) 으로 보여지게 한다.

C#

  
        private void Form1_Load(object sender, EventArgs e)
        { 
            this.hHippoChart1.DrawChart();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            e.Result = Draw((int)e.Argument, worker, e);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                resultLabel.ForeColor = Color.Red;
                resultLabel.Text = "데이터 수신을 중지합니다...";
            }
            else
            {
                resultLabel.Text = e.Result.ToString();
            } 
        }

        private long Draw(double data, BackgroundWorker worker, DoWorkEventArgs e)
        {
            this.progressBar1.Maximum = userMaxCount;

            if (currentValue >= 20)
            {
                currentValue = 0;
            }

            SeriesItem item = new SeriesItem((float)data);
            item.Points = new Points();
            item.Points.Width = 4;
            item.Points.PointType = PointType.FillCircle;
            item.Name = DateTime.Now.ToString("mm:ss");

            this.hHippoChart1.DrawRealTimeChart(item, userMaxCount);

            long result = 0;

            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                Random rr1 = new Random();
                worker.ReportProgress(currentValue);
                currentValue++;

                resultLabel.ForeColor = Color.Green;
                resultLabel.Text = "데이터 수신 중 입니다...";

                System.Threading.Thread.Sleep(1000);

                this.Draw(rr1.Next(100), worker, e);
            }

            return result;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.hHippoChart1.SeriesListDictionary.Clear();

            SeriesList sList = new SeriesList();
            sList.AxisFactor.YAxis.IsAutoSetting = false;
            sList.AxisFactor.YAxis.MaxUnitValue = 100;
            sList.AxisFactor.YAxis.MinUnitValue = 0;
            sList.AxisFactor.YAxis.Interval = 10;

            sList.SeriesCollection.Add(new Series());

// 히포차트 3.0 이상 버전 부터는 아래 코드를 삽입해야합니다.
 // 시리즈의 개수만큼 똑같이 추가합니다.
   this.hHippoChart1.RealTimeList.Add(new Hippo.ChartControl.HippoRealTimeAttribute());


            this.hHippoChart1.SeriesListDictionary.Add(sList);

            resultLabel.ForeColor = Color.Blue;
            resultLabel.Text = "데이터 수신을 시작합니다...";

            this.backgroundWorker1.RunWorkerAsync(0);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.CancelAsync();
        }


VB

 Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    Me.hHippoChart1.DrawChart()
End Sub

Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    Dim worker As BackgroundWorker = TryCast(sender, BackgroundWorker)
   
    e.Result = Draw(CInt(e.Argument), worker, e)
End Sub

Private Sub backgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
    Me.progressBar1.Value = e.ProgressPercentage
End Sub

Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
    If e.[Error] IsNot Nothing Then
        MessageBox.Show(e.[Error].Message)
    ElseIf e.Cancelled Then
        resultLabel.ForeColor = Color.Red
        resultLabel.Text = "데이터 수신을 중지합니다..."
    Else
        resultLabel.Text = e.Result.ToString()
    End If
End Sub

Private Function Draw(ByVal data As Double, ByVal worker As BackgroundWorker, ByVal e As DoWorkEventArgs) As Long
    Me.progressBar1.Maximum = userMaxCount
   
    If currentValue >= 20 Then
        currentValue = 0
    End If
   
    Dim item As New SeriesItem(CSng(data))
    item.Points = New Points()
    item.Points.Width = 4
    item.Points.PointType = PointType.FillCircle
    item.Name = DateTime.Now.ToString("mm:ss")
   
    Me.hHippoChart1.DrawRealTimeChart(item, userMaxCount)
   
    Dim result As Long = 0
   
    If worker.CancellationPending Then
        e.Cancel = True
    Else
        Dim rr1 As New Random()
        worker.ReportProgress(currentValue)
        currentValue += 1
       
        resultLabel.ForeColor = Color.Green
        resultLabel.Text = "데이터 수신 중 입니다..."
       
        System.Threading.Thread.Sleep(1000)
       
        Me.Draw(rr1.[Next](100), worker, e)
    End If
   
    Return result
End Function

Private Sub btnStart_Click(ByVal sender As Object, ByVal e As EventArgs)
    Me.hHippoChart1.SeriesListDictionary.Clear()
   
    Dim sList As New SeriesList()
    sList.AxisFactor.YAxis.IsAutoSetting = False
    sList.AxisFactor.YAxis.MaxUnitValue = 100
    sList.AxisFactor.YAxis.MinUnitValue = 0
    sList.AxisFactor.YAxis.Interval = 10
   
    sList.SeriesCollection.Add(New Series())
   
    Me.hHippoChart1.SeriesListDictionary.Add(sList)
   
    resultLabel.ForeColor = Color.Blue
    resultLabel.Text = "데이터 수신을 시작합니다..."
   
    Me.backgroundWorker1.RunWorkerAsync(0)
End Sub

Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs)
    Me.backgroundWorker1.CancelAsync()
End Sub


이상 간단히 알아보았습니다. 데이터는 편의상 랜덤으로 생성하였습니다. 사용시에는 우선 코드 복사 후 데이터 받는 부분만 구현하시면 되겠습니다.
사업자 정보 표시
히포차트 | 하영대 | 경기도 성남시 수정구 복정동 631-5 401 | 사업자 등록번호 : 129-34-55719 | TEL : 031-751-6673 | Mail : hippochart@gmail.com | 통신판매신고번호 : 제 2010-경기성남-1203호 | 사이버몰의 이용약관 바로가기

Posted by 리바이 병장
,


/* 다음 웹인사이드 로그 분석*/