퇴근5분전

 

 최근에 나온 task나 await 는 못써봤다. 가끔 문서는 봤는데 어렵더랑...

간단하게 비동기 처리를 할 수 있는 옛날 버젼으로다가.

정리해본다. ( 전에 해둔것 같은데 못찾겠다... )

 

 delegate void Async<T>(T ctrl, Action begin, Action complite) where T : Control;
        Async<Control> async = (ctrl, begin, complite) =>
        {
            if (begin != null)
            {

               // 비동기 처리 시작!
                begin.BeginInvoke((ir) => {
                    begin.EndInvoke(ir);

               // 종료...
                    ctrl.DoInvoke(c =>
                    {
                        complite();
                    });
                }, begin);
            }
        };

 

// 컨트롤의 크로스 스레드 작업이 잘못되었습니다. 의 메세지를 회피할 수 있는 확장 메서드다.

 public static class Ex
    {
        public static void DoInvoke<T>(this T ctrl, Action<T> callMethod) where T : Control
        {
            if (ctrl.InvokeRequired)
            {
                ctrl.Invoke(new Action<T, Action<T>>(DoInvoke), ctrl, callMethod);
            }
            else
            {
                callMethod(ctrl);
            }
        }
    }

 

 

대리자 하나를 선언한다.

   : begin~~~~처리 ~~~~~complite

 

테스트!!!

폼에 버튼 하나를 둔다. ( : 추후에 프로그래스 바를 움직을 것임. )

 

 

 

테스트에 실행될 메서드

        bool isRun = false;
        void DemoAsyncMethod()
        {
            while (isRun)
            {
                System.Threading.Thread.Sleep(10000);// 10sec
                isRun = false;
            }
        }

 

 

아무런 처리를 하지 않았을때...

 private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            isRun = true;
            DemoAsyncMethod();
            button1.Enabled = true;
        }

 실행하면 비동기 버튼은 비활성화 되면서 DemoAyncMethod가 실행되면서 10초간 꼼짝도 하지 않는다.

이렇게 되면 사용자는 ...

그래서 비동기 처리를 해봤다.

private void button1_Click(object sender, EventArgs e)
        {
            // button1.Enabled = false;
            async(this, () => // begin Invoke ~ endInvoke
            {
                button1.Enabled = false;  // 크로스 쓰레드 error가 발생한다. 
                // button1.DoInvoke(b => b.Enabled = false); 주석을 해제하고 위 라인을 삭제하면 Invoke 처리로 정상 동작을 할 수 있다. 
                isRun = true;
                DemoAsyncMethod();
            }, () =>  // async complite
            {
                button1.Enabled = true;
            });
        }

 

 실행을 하면 버튼이 비활성화 된채 폼을 이리저리 움직여도 아까와 다르게 움직여진다...

 

좀더 시각적 효과를 주기위해 프로그래스를 기능을 포함한다.

bool isRun = false;
        void DemoAsyncMethod()
        {
            int progressValue = 0;
            while (isRun)
            {
                progressBar1.DoInvoke(p => p.Value = (++progressValue) * 10);
                System.Threading.Thread.Sleep(1000);// 10sec
                if (progressValue >= 10) isRun = false;
            }
        }

 

 

 

 

 

'# 1) 프로그래밍' 카테고리의 다른 글

Visual studio Community 2013 설치!  (0) 2014.12.07
app.config Section 작성 변환기...  (0) 2014.11.05
before, do, after를 묶어보자!!  (0) 2014.10.28
ExtJs > ExtNet 변환 툴!!!  (0) 2014.07.10
Directory.Create 관련...  (0) 2014.06.09