Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created June 4, 2012 16:09
Show Gist options
  • Save masaru-b-cl/2869254 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/2869254 to your computer and use it in GitHub Desktop.
非同期メソッドのシミュレーションにもasync/await
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 待ちが必要なのでTaskを受け取る
var task = DoSomething();
Console.WriteLine("Waiting...");
task.Wait(); // Waitで明示的に待つ
}
// asyncつけると
private static async Task DoSomething()
{
// awaitが使え、同期処理と同じような感じで戻り値が取れる
var s = await AsyncMethod("Sho");
Console.WriteLine(s); // コールバックとして実行される
}
private static async Task<string> AsyncMethod(string name)
{
await Task.Delay(3000);
return "Hello world, " + name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment