Re: [問題] 測試小朋友九九乘法表的程式問題

看板C_Sharp作者 (葡萄神手)時間12年前 (2011/11/14 09:58), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
原文推文中有鄉民提出用遞回函數 但是遞回函數會導致堆棧耗盡(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
文章代碼(AID): #1Em7NE4H (C_Sharp)
文章代碼(AID): #1Em7NE4H (C_Sharp)