- 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(() =>
{
String tmp = second.ToString() + " => " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff") + "<br />";
for (var i = 0; i < 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>> GetAll()
{
Task<list<string>> result = Task<list<string>>.Run(() =>
{
var taskList = new List<task<string>>();
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>> resultList = Task.Run<list<string>>(async () => await AsyncTask.GetAll());
return resultList.Result;
}
}
}