본문 바로가기

.Net

C# Sync 메소드에서 Async 메소드 호출

  • HomeController
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Library;
namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List<String> result = AsyncTask.Get();
            ViewData["result"] = result as List<String>;
            return View();
        }
    }
}
 
  • AsyncTask.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Library
{
    public static class AsyncTask
    {
        public static async Task<string> GetResult(Int32 second)
        {
           
            Task<string> result = Task<string>.Run(() =&gt;
            {
                String tmp = second.ToString() + " => " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff") + "<br />";
                for (var i = 0; i &lt; second * 100000; i++)
                {
                    // delay~~~
                }
                tmp += second.ToString() + " => " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff");
                return tmp;
            });
            return await result;
        }
        public static Task<list<string>&gt; GetAll()
        {
            Task<list<string>&gt; result = Task<list<string>&gt;.Run(() =&gt;
            {
                var taskList = new List<task<string>&gt;();
                taskList.Add(AsyncTask.GetResult(5000));
                taskList.Add(AsyncTask.GetResult(4000));
                taskList.Add(AsyncTask.GetResult(3000));
                taskList.Add(AsyncTask.GetResult(2000));
                taskList.Add(AsyncTask.GetResult(1000));
                taskList.Add(AsyncTask.GetResult(2000));
                taskList.Add(AsyncTask.GetResult(3000));
                taskList.Add(AsyncTask.GetResult(4000));
                taskList.Add(AsyncTask.GetResult(5000));
                Task<string[]> tmp = Task.WhenAll(taskList.ToArray());
                return tmp.Result.ToList();
            });
            return result;
        }
        public static List<string> Get()
        {
            Task<list<string>&gt; resultList = Task.Run<list<string>&gt;(async () =&gt; await AsyncTask.GetAll());
            return resultList.Result;
        }
       
    }
}