본문 바로가기

C#/수업 내용

Task, Task<TResult>

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace HelloWorld
{
    public class App
    {
        //생성자
        public App()
        {
            Action action2 = () => { };
            Task t1 = new Task(action2);

            //Action<object> action = (obj) => { };
            Action<object> action = MyAction;
            //                      매개변수 obj
            Task t2 = new Task(action, "alpha");

            Task t3 = Task.Factory.StartNew(action, "beta");
            t3.Wait();

            t2.Start();
            Console.WriteLine("Hello Wrold!");

            string obj = "delta";
            Task t4 = Task.Run(() => {
                Console.WriteLine("{0}, {1}", Thread.CurrentThread.ManagedThreadId, obj);
            });

            t4.Wait();
        }

        void MyAction(object obj)
        {
            Console.WriteLine("{0}, {1}", Thread.CurrentThread.ManagedThreadId, obj);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace HelloWorld
{
    public class App
    {
        //생성자
        public App()
        {
            //반환값부터 작성하고 값에 맞게 <Type>작성
            //Task<int> task = Task<int>.Run(() =>
            //{
            //    return 100;
            //});

            Task<int> task = Task<int>.Factory.StartNew(() =>
            {
                return 100;
            });

            Console.WriteLine("result: {0}", task.Result);
        }
    }
}

 

'C# > 수업 내용' 카테고리의 다른 글

세미 평가  (0) 2021.12.24
비동기 프로그래밍  (0) 2021.12.24
스레드  (0) 2021.12.24
반복기  (0) 2021.12.24
event  (0) 2021.12.24