Singleton Patternを使用して単純なクラスを構築しようとしています。
私が達成しようとしているのは、非同期メソッド呼び出しの結果の処理を担当するメイン クラス 2 関数を使用することです。1 つは正しい結果を処理し、2 番目はすべてのエラーを処理します。
すべての非同期操作を行うクラスは次のようになります。
class EWS : SingletonBase<EWS>
{
private EWS()
{
//private constructor
}
private int LongRunningMethod(Action<string> error)
{
int x = 0;
for (int i = 0; i < 10; i++)
{
//Console.WriteLine(i);
x += i;
Thread.Sleep(1000);
}
//here I can do try...catch and then call error("Description")
return x;
}
public class CommandAndCallback<TSuccess, TError>
{
public TSuccess Success { get; set; }
public TError Error { get; set; }
}
public void DoOperation(Action<int> success, Action<string> error)
{
Func<Action<string>, int> dlgt = LongRunningMethod;
//Func<Action<string>, int> dlgt = new Func<Action<string>, int>(LongRunningMethod);
CommandAndCallback<Action<int>, Action<string>> callbacks = new CommandAndCallback<Action<int>, Action<string>>() { Success = success, Error = error };
IAsyncResult ar = dlgt.BeginInvoke(error,MyAsyncCallback, callbacks);
}
public void MyAsyncCallback(IAsyncResult ar)
{
//how to access success and error here???
int s ;
Func<Action<string>, int> dlgt = (Func<Action<string>,int>)ar.AsyncState;
s = dlgt.EndInvoke(ar);
//here I need to call success or error that were passed to DoOperation
}
}
私のメインクラスでは、次のようにメソッドを呼び出したいと思います:
private void Operation_OK(int count)
{
//here handle OK
}
private void Operation_ERROR(string error)
{
//here handle ERROR
}
private void button1_Click(object sender, EventArgs e)
{
EWS.Instance.DoOperation(Operation_OK, Operation_ERROR);
}
上記のように呼び出すことができるように、EWS クラスをどのように変更すればよいですか。
デリゲートの代わりにラムダ式を使用するには?
このようなメソッドを呼び出すのは良い考えですか? クラスに 2 つまたは 3 つのメソッドが必要で、それらをすべてのフォームで独立して呼び出すことができます。