作者linxiaoxi (葡萄神手)
看板C_Sharp
标题Re: [问题] 测试小朋友九九乘法表的程式问题
时间Mon Nov 14 09:58:36 2011
原文推文中有乡民提出用递回函数
但是递回函数会导致堆栈耗尽(stack overflow)
其实可以使用异步方式来避免这种情况
internal class Multip
{
private AsyncCallback _callback;
private MultipAsyncResult _asyncResult;
private int[] com;
internal void BeginQuestion(AsyncCallback callback, object state)
{
this._callback = callback;
this._asyncResult = new MultipAsyncResult(state);
ThreadPool.QueueUserWorkItem(new WaitCallback(this.Question));
}
internal int[] EndQuestion(IAsyncResult ar)
{
return this.com;
}
private void Question(object obj)
{
System.Random number = new Random();
int a = number.Next(1, 9);
int b = number.Next(1, 9);
Console.WriteLine("How much is {0} times {1}?", a, b);
int input = Convert.ToInt32(Console.ReadLine());
int ans = a * b;
this.com = new int[] { input, ans };
this._callback(this._asyncResult);
}
internal class MultipAsyncResult : IAsyncResult
{
private object asyncState;
public MultipAsyncResult(object state)
{
this.asyncState = state;
}
#region IAsyncResult 成员
public object AsyncState
{
get { return this.asyncState; }
}
public System.Threading.WaitHandle AsyncWaitHandle
{
get { throw new Exception("The method or operation is not im
plemented."); }
}
public bool CompletedSynchronously
{
get { throw new Exception("The method or operation is not im
plemented."); }
}
public bool IsCompleted
{
get { throw new Exception("The method or operation is not im
plemented."); }
}
#endregion
}
}
以上为异步class代码,在main函数中使用示例如下
class Program
{
static AutoResetEvent are = new AutoResetEvent(false);
static void Main(string[] args)
{
Multip mul = new Multip();
mul.BeginQuestion(new AsyncCallback(Test), mul);
are.WaitOne();
}
static void Test(IAsyncResult ar)
{
Multip mul = ar.AsyncState as Multip;
int[] com = mul.EndQuestion(ar);
mul.BeginQuestion(new AsyncCallback(Test), mul);
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 1.202.244.1
1F:推 summerpurple:感谢! 11/14 10:41