본문 바로가기

Visual Basic.Net

BeginInvoke 와 Invoke

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication7
{
    public delegate void TestThread(int x, string str);
    class TestClass
    {
        public void TestThreadF(int x, string str)
        {
            Thread.Sleep(x);
            Console.WriteLine(str);
        }
    }

    class Program
    {

 

        public static void Main(string[] args)
        {
            TestClass ThreadC = new TestClass();
            TestThread Test = new TestThread(ThreadC.TestThreadF);
            //int j = int.Parse(Console.ReadLine());
            // string str = Console.ReadLine();

            IAsyncResult Result = Test.BeginInvoke(10000, "BeginInVoke", null, null);//새로운 쓰래드 생성

                                                                                                                  //10000, "BeginInVoke" 는 TestThreadF의 인자값 
            Test.Invoke(1000, "InVoke");//현재 큐안에 집어넣음
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("TestMainThread");

            }
            Test.EndInvoke(Result);//Test.BeginInvoke가 끗날때끼지 대기.
            //Thread.Sleep(10000);
            //Test.EndInvoke;
            //string str2 = Test.EndInvoke(Result);
            //Console.WriteLine(str2.ToString());
        }
    }
}


------------------------------------------------------------------------------------------------



using System.Threading;

 

    class CUser
    {
        WaitCallback async;
        IAsyncResult ar;

 

        public void Start()
        {
            async = new WaitCallback(OnThread);
            ar = async.BeginInvoke(this, null, null);
        }

 

        public void Wait()
        {
            if (async != null)
                async.EndInvoke(ar);
        }

 

        void OnThread (object state)
        {
            Console.WriteLine("작업시작");

 

            // 작업처리
            Thread.Sleep(3000);

 

            Console.WriteLine("작업종료");
        }
    }