我正在尝试使用Singleton Pattern构建简单的类。
我想要完成的是在我的主要类 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 类,以便我可以像上面所示那样调用它。
如何使用 lambda 表达式代替委托?
调用这样的方法是个好主意吗?我需要在我的班级中有 2 或 3 个方法,并且能够以所有形式独立地调用它们。