Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created June 4, 2012 15:33
Show Gist options
  • Save masaru-b-cl/2869067 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/2869067 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 Task<string> AsyncMethod(string name)
{
// 非同期メソッドとして、Task.RunでTaskを実行して返す
return Task.Run(() =>
{
Thread.Sleep(3000);
return "Hello world, " + name;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment