Created
June 4, 2012 15:33
-
-
Save masaru-b-cl/2869067 to your computer and use it in GitHub Desktop.
async/awaitってこんな感じですね
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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