Created
July 7, 2014 13:01
-
-
Save devlights/b1362b5c2d3e5492f25b to your computer and use it in GitHub Desktop.
C# 5.0 async/await でのMainメソッドの書き方
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
class Program | |
{ | |
static void Main() | |
{ | |
// | |
// Mainメソッドはasync付けられないので | |
// 一階層挟んでタスクを待ち合わせするようにする | |
// | |
ExecMainProc().Wait(); | |
} | |
internal static async Task ExecMainProc() | |
{ | |
try | |
{ | |
// | |
// 実際のメイン処理を待機する処理を記述. | |
// ここはMainメソッドではないのでawaitが使える | |
// | |
await new Program().Exec(); | |
} | |
catch (Exception ex) | |
{ | |
// | |
// Mainメソッドに対して例外を飛ばさないよう | |
// ここで例外を捕らえる。awaitしているので | |
// AggregateExceptionをキャッチする必要は無い | |
// | |
Console.WriteLine(ex); | |
} | |
} | |
internal async Task Exec() | |
{ | |
// | |
// 処理を記述. | |
// | |
// 以下では例としてStackExchange.Redisを | |
// 利用してRedisに非同期アクセスしている. | |
// | |
var connection = await ConnectionMultiplexer.ConnectAsync("接続文字列"); | |
var db = connection.GetDatabase(); | |
await db.StringSetAsync("Key1", "日本語の文字列"); | |
var jsonString = GetJsonString(); | |
await db.StringSetAsync("Key2", jsonString); | |
var result = await db.StringGetAsync("Key1"); | |
var result2 = await db.StringGetAsync("Key2"); | |
Console.WriteLine(result); | |
Console.WriteLine(result2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment