class Program
{
private static int threadId;
static void Main(string[] args)
{
AsyncDemo ad = new AsyncDemo();
AsyncDelegate dlgt = ad.TestMethod;
IAsyncResult ar = dlgt.BeginInvoke(3000, out threadId, new AsyncCallback(CallbackMethod), dlgt);
Console.WriteLine("Press Enter to close application.");
Console.ReadLine();
}
static void CallbackMethod(IAsyncResult ar)
{
AsyncDelegate dlgt = (AsyncDelegate)ar.AsyncState;
string ret = dlgt.EndInvoke(out threadId, ar);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret);
}
}
public delegate string AsyncDelegate(int callDuration, out int threadId);
public class AsyncDemo
{
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return "MyCallTime was " + callDuration.ToString();
}
}
怎样在BeginInvoke的时候直接用一条lambda表达式把回调方法加进去,而不单独定义static void CallbackMethod(IAsyncResult ar)这个方法呢。。高手进
IAsyncResult ar = dlgt.BeginInvoke(3000, out threadId, (o) => { AsyncDelegate dlgt1 = (AsyncDelegate)o.AsyncState; string ret = dlgt1.EndInvoke(out threadId, o); Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret); }, dlgt);
这样写不能实现,,你可以拷过去自己试试。。。这种写法我已经试过的了。就是不行才上来问问的。。就是不知道哪里出了问题!!!!!!!
IAsyncResult ar = dlgt.BeginInvoke(3000, out threadId, (r) =>
{
AsyncDelegate AsyncState = (AsyncDelegate)r.AsyncState;
string ret = AsyncState.EndInvoke(out threadId, r);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret);
}, dlgt);
这样写不能实现,,你可以拷过去自己试试。。。这种写法我已经试过的了。就是不行才上来问问的。。就是不知道哪里出了问题!!!!!!!
@彬彬@科比: 我肯定是本地试过可以才发上来的,你觉得那里有问题。
就是改成这样??你能运行。。能write出来???
class Program
{
private static int threadId;
static void Main(string[] args)
{
AsyncDemo ad = new AsyncDemo();
AsyncDelegate dlgt = ad.TestMethod;
IAsyncResult ar = dlgt.BeginInvoke(3000, out threadId, (r) =>
{
AsyncDelegate AsyncState = (AsyncDelegate)r.AsyncState;
string ret = AsyncState.EndInvoke(out threadId, r);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret);
}, dlgt);
}
static void CallbackMethod(IAsyncResult ar)
{
AsyncDelegate dlgt = (AsyncDelegate)ar.AsyncState;
string ret = dlgt.EndInvoke(out threadId, ar);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret);
}
}
public delegate string AsyncDelegate(int callDuration, out int threadId);
public class AsyncDemo
{
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return "MyCallTime was " + callDuration.ToString();
}
}
@geass..: 真试过的??!!
@彬彬@科比: 你先自己本地认真测试,阅读MSDN之后再上来发帖。
@geass..: 可以了,我有个地方弄错了。谢了
(arg1,arg2)=>{c#语句};
上面的 都行
@geass..: 真试过的??!!