I am writing an asynchronous class to simplify function operation. Below is my code:
using System;
namespace AsyncLibery
{
public class AsyncLibery
{
delegate void Exec(); // No input parameter, no return value
delegate void ExecWithParams<T>(T T1); //One input parameter, no return value
delegate void ExecWithParams<T1, T2>(T1 t1,T2 t2); //Two input parameters, no return value
delegate void ExecWithParams<T1, T2, T3>(T1 t1, T2 t2, T3 t3);//Three input parameters, no return value
delegate void ExecWithParams<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4);//Four input parameters,no return value
delegate T ExecWithReturnType<T>(); //No input parameter, one return value
delegate T2 ExecWithReturnType<T1, T2>(T1 t1); //One input parameter, one return value
delegate T3 ExecWithReturnType<T1, T2, T3>(T1 t1, T2 t2);//Two input parameters, one return value
delegate T4 ExecWithReturnType<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3);//Three input parameters, one return value
delegate T5 ExecWithReturnType<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4);// Four input parameters, one return value.
#region no input parameter, no return value
public void BeginInvokeEx(Action actionFunction)
{
Exec exec = new Exec(actionFunction);
exec.BeginInvoke(new AsyncCallback(EndInvokeEx), exec);
}
private void EndInvokeEx(IAsyncResult iar)
{
Exec exec = (Exec)iar.AsyncState;
exec.EndInvoke(iar);
}
#endregion
#region one input parameter, no return value
public void BeginInvokeEx<T>(Action<T> actionFunction,T T1)
{
ExecWithParams<T> exec = new ExecWithParams<T>(actionFunction);
exec.BeginInvoke(T1, new AsyncCallback(EndInvokeEx1), exec);
}
private void EndInvokeEx1(IAsyncResult iar)
{
ExecWithParams<T> exec = (ExecWithParams<T>)iar.AsyncState;
exec.EndInvoke(iar);
}
#endregion
}
}
When I complied the code, it throws me an exception like "The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)", the exception is appeared at below code :
ExecWithParams<T> exec = (ExecWithParams<T>)iar.AsyncState;
I know that we must refer T parameter the specific type like int or string or anything else. But who can help me without modifying the T parameter? is there any good method to deal with it? thx.
Make
EndInvokeEx1
generic:And change your
BeginInvokeEx
accordingly: