BeginInvoke, EndInvoke leaves extra thread

N

Nick Palmius

Hello,

I am experimenting with async callbacks using BeginInvoke and EndInvoke, and
although my code which I have shown below works, when the program stops at
the end (on the ReadLine()), there are still 2 threads running if i pause
the execution, even if I kow that EndInvoke has been called on the thread.
This also happens in the async callback sample on msdn. Is this anything I
need to wory about, because it doesn't seen too good to me??

Also, if you want to share resources between threads, is it enough to
declare it volatile, or should I lock it as well?? And, erm, how does one go
about locking variables in c#?

Cheers,
Nick.


using System;
using System.Runtime.Remoting.Messaging;
class AsyncTestClass
{
public delegate void AsyncTestDel (int Num1, int Num2, int Num3);
public static void AsyncTest(int Num1, int Num2, int Num3)
{
Console.WriteLine(Num1);
Console.WriteLine(Num2);
Console.WriteLine(Num3);
}
public static void Finished(IAsyncResult ar)
{
// Extract the delegate from the AsyncResult.
AsyncTestDel fd = (AsyncTestDel)((AsyncResult)ar).AsyncDelegate;

// Free up resourses
fd.EndInvoke(ar);

Console.WriteLine("Callback Finished");
}
static void Main()
{
// Stops the app, only one thread running here
Console.Write("Press any key to start demo >");
Console.ReadLine();

// Create delegate and begin Async invocation
AsyncTestDel d = new AsyncTestDel(AsyncTest);
// Even if you call this many times, you will
// still only be left with one thread.
d.BeginInvoke(105, 106, 107,
new AsyncCallback(Finished), null);

// Do some work
for (int i = 0; i < 100; i++)
Console.WriteLine(i);

// Break program here, there are now 2 threads...
Console.Write("Press any key to end >");
Console.ReadLine();
}
}
 
J

Jon Skeet [C# MVP]

Nick Palmius said:
I am experimenting with async callbacks using BeginInvoke and EndInvoke, and
although my code which I have shown below works, when the program stops at
the end (on the ReadLine()), there are still 2 threads running if i pause
the execution, even if I kow that EndInvoke has been called on the thread.
This also happens in the async callback sample on msdn. Is this anything I
need to wory about, because it doesn't seen too good to me??

It's a thread-pool thread. Nothing to worry about.
Also, if you want to share resources between threads, is it enough to
declare it volatile, or should I lock it as well?? And, erm, how does
one go about locking variables in c#?

See http://www.pobox.com/~skeet/csharp/multithreading.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top