Re: [問題] 測試小朋友九九乘法表的程式問題
原文推文中有鄉民提出用遞回函數
但是遞回函數會導致堆棧耗盡(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
推
11/14 10:41, , 1F
11/14 10:41, 1F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):