using System;
using ;
using ;
using ;
using ;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
("Main ThreadId = " + );
//Assign a value to the delegation
Func<long, long> delegateMethod = new Func<long, long>(CalcSum);
//Asynchronously execute the delegation, here the delegation itself is passed in as an asyncState object. In the callback function, you need to use the delegate's EndInvoke to obtain the result.
(200, DoneCallback, delegateMethod);
//Execute the delegation asynchronously, throw an exception
(10000000000, DoneCallback, delegateMethod);
();
}
//Delegate callback function
static void DoneCallback(IAsyncResult asyncResult)
{
//The delegation has been executed in the asynchronous thread here
("DoneCallback ThreadId = " + );
Func<long, long> method = (Func<long, long>);
//Exception of delegated execution will be thrown when EndInvoke
try {
//When using BeginInvoke, the entrusted EndInvoke is passed into the calculation result. At this time, the calculation result has been released. If there is an exception, it will be thrown here.
long sum = (asyncResult);
("sum = {0}",sum);
}
catch (OverflowException)
{
("Operation overflow");
}
}
//Delegation method
static long CalcSum(long topLimit)
{
//The delegate starts execution in another thread
("Calc ThreadId = " + );
checked
{
long result = 0;
for (long i = 0; i < topLimit; i++)
{
result += i;
}
return result;
}
}
}
}