Last active
May 22, 2016 04:59
-
-
Save nuitsjp/330cbb194f3ffa13f838135c5519da3a to your computer and use it in GitHub Desktop.
非同期化
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.Threading.Tasks; | |
namespace SingletonSample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
private async void Run() | |
{ | |
// 初回一回だけ初期化処理をする | |
// AppのOnStartとか最初の画面のVMの初期化処理時とかが良いかも | |
await SingletonClass.Instance.Initialize(); | |
Console.WriteLine(await SingletonClass.Instance.GetValue()); | |
Console.WriteLine(await SingletonClass.Instance.GetValue()); // どこからも同じインスタンスを参照できる | |
await SingletonClass.Instance.SetValue("foo"); | |
Console.WriteLine(await SingletonClass.Instance.GetValue()); | |
} | |
} | |
/// <summary> | |
/// システム全体から一つしかインスタンスが存在しないことを保証するクラス。 | |
/// 「シングルトン=たった一つの」を保証するデザインパターン | |
/// </summary> | |
public class SingletonClass | |
{ | |
/// <summary> | |
/// たった一つのインスタンス | |
/// </summary> | |
public static SingletonClass Instance { get; } = new SingletonClass(); | |
private string value; | |
/// <summary> | |
/// インスタンスが一つきりであることを保証するためコンストラクタは隠ぺいする | |
/// </summary> | |
private SingletonClass() | |
{ | |
} | |
/// <summary> | |
/// なんか初期化メソッド | |
/// </summary> | |
public Task Initialize() | |
{ | |
return Task.Run(() => | |
{ | |
// ここでjson読んでデシリアライズ処理すると良いかも。 | |
// 重たい処理を想定 | |
value = "hoge"; | |
}); | |
} | |
public Task<string> GetValue() | |
{ | |
return Task.Run(() => | |
{ | |
return value; | |
}); | |
} | |
public Task SetValue(string value) | |
{ | |
return Task.Run(() => | |
{ | |
this.value = value; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment