Hello everyone,especially Microsoft Employees……:-)
I'm now doing something with the help of Delegate BeginInvoke and EndInvoke……Look at my codes:
namespace CSharp
{
public class Program
{
static int a = 0;
int Fun()
{
Console.WriteLine("This is a fun function with a return value……");
return 1;
}
static void Main(string[] args)
{
Func<int> a1 = new Func<int>(new Program().Fun);
AsyncCallback ac = new AsyncCallback(
delegate(IAsyncResult asc)
{
if (asc.IsCompleted)
{
//Here dealling with "a"
Console.WriteLine(a+1);
}
});
var result = a1.BeginInvoke(ac, null);
while (!result.IsCompleted) Thread.Sleep(10);
a1.EndInvoke(result);
}
}
}
Two questions:
1)If I want to use the result from Func<int>,must I declare the result container variable (in C# codes it is "a")in the whole class as a global one?
2)If I comment (or delete Thread.Sleep(10)),Console.WriteLine(a+1) cannot be executed……Why?
1)If I want to use the result from Func<int>,must I declare the result container variable (in C# codes it is "a")in the whole class as a global one?
No,that's not a need——because we can call EndInvoke to get the result and do things in the IAsyncResult in the IsCompleted event.
TimoYang
If I comment (or delete Thread.Sleep(10)),Console.WriteLine(a+1) cannot be executed……Why?
BeginInvoke will start a thread, so if you don't use Thread.Sleep(10) the main thread will hung up and never responses……So the extended thread will never get the chance to be executed!
Marked as answer by TimoYang on Apr 15, 2012 08:53 AM
TimoYang
Contributor
3732 Points
1275 Posts
BeginInvoke & EndInvoke for Delegate
Apr 15, 2012 05:20 AM|LINK
Hello everyone,especially Microsoft Employees……:-)
I'm now doing something with the help of Delegate BeginInvoke and EndInvoke……Look at my codes:
namespace CSharp { public class Program { static int a = 0; int Fun() { Console.WriteLine("This is a fun function with a return value……"); return 1; } static void Main(string[] args) { Func<int> a1 = new Func<int>(new Program().Fun); AsyncCallback ac = new AsyncCallback( delegate(IAsyncResult asc) { if (asc.IsCompleted) { //Here dealling with "a" Console.WriteLine(a+1); } }); var result = a1.BeginInvoke(ac, null); while (!result.IsCompleted) Thread.Sleep(10); a1.EndInvoke(result); } } }Two questions:
1)If I want to use the result from Func<int>,must I declare the result container variable (in C# codes it is "a")in the whole class as a global one?
2)If I comment (or delete Thread.Sleep(10)),Console.WriteLine(a+1) cannot be executed……Why?
Thxxxx
TimoYang
Contributor
3732 Points
1275 Posts
Re: BeginInvoke & EndInvoke for Delegate
Apr 15, 2012 08:53 AM|LINK
Sorry men……I think I know the answers!!!!!!!!!!!
No,that's not a need——because we can call EndInvoke to get the result and do things in the IAsyncResult in the IsCompleted event.
BeginInvoke will start a thread, so if you don't use Thread.Sleep(10) the main thread will hung up and never responses……So the extended thread will never get the chance to be executed!