I am running a Delegate Async Callback pattern on a fibonacci method. This static method contains a loop where the thread sleeps for 300ms to print out the background Thread pool Id. Unfortunately, in my FibCompleted() the EndInvoke method is terminating my process. Any tips would be helpful. Thank you.
public delegate int FibPointer(int x); // FibbonaciSequence() pointer
class Program
{
static void Main(string[] args)
{
// fibonacci Length
int fibLength = 8;
// point delegate to method
FibPointer fb = new FibPointer(FibonacciSequence);
IAsyncResult iftAR = fb.BeginInvoke(
fibLen, new AsyncCallback(FibCompleted), null);
Console.WriteLine("Fibonacci process now running on thread {0}\n",
Thread.CurrentThread.ManagedThreadId);
int count = 0;
while (!iftAR.IsCompleted) // completion occurs when userIN length is reached
{
// run fib sequence.
Console.WriteLine("{0}", FibonacciSequence(count));
count++;
}
Console.ReadKey();
}
static int FibonacciSequence(int num)
{
int num1 = 0, num2 = 1, res = 0;
if (num == 0) return 0;
if (num == 1) return 1;
for (int i = 0; i < num; i++)
{
res = num1 + num2;
num1 = num2;
num2 = res;
Thread.Sleep(300);
// track background thread from pool
Console.WriteLine("Working on thread: {0}",
Thread.CurrentThread.ManagedThreadId);
}
return res;
}
static void FibCompleted(IAsyncResult ar)
{
Console.WriteLine("\nFib Sequence Completed.");
// retrieve result
AsyncResult res = (AsyncResult)ar;
//FibPointer fp = ar.AsyncState as FibPointer;
FibPointer fp = res.AsyncDelegate as FibPointer;
// call EndInvoke to grab results
string returnVal = fp.EndInvoke(ar).ToString();
Console.WriteLine("\nreturn val is: {0}", returnVal);
}
}