ren
ren

Reputation: 3993

is there a difference between ThreadPool.QueueUserWorkItem and delegate BeginInvoke

I need efficient (using fewest threads possible) asynchronous way of doing computation (and I use .net 4). One way is to

ThreadPool.QueueUserWorkItem(f => job.DoWork()); 
job.Completed += (a, b) => {...} //Completed is event I fire when work is done

The other possibility is to implement async method as is done prior to C# v.5, which is basically calling BeginInvoke on a delegate.

My question is: is there a difference between these two other than different syntax, as it seems BeginInvoke is also using a new thread from ThreadPool?

As an aside: is it possible to define and call a method asynchronously on the same thread as the caller (as is done in javascript) (in any version of C#)?

Upvotes: 0

Views: 2354

Answers (3)

Martin Mulder
Martin Mulder

Reputation: 12944

Delegate.BeginInvoke puts that method at the ThreadPool. The advantage of BeginInvoke is that you can use the IAsyncResult, which can be used to monitor the progress of the asynchronous call. Its 'brother' method, EndInvoke, retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes.

See: http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

Upvotes: 1

Dirk
Dirk

Reputation: 10958

I'd take a look at the Task Parallel Library and the Task class. The Task Parallel Library (TPL) offers parallel execution of loops, and the Task class allows you some control in which thread a task should execute, which is important for UI operations.

Upvotes: 1

metadings
metadings

Reputation: 3848

There's no better answer than to recommend you to read Joseph Albahari's (partially free) book about Threading in C#.

Asynchronous delegates

ThreadPool.QueueUserWorkItem doesn’t provide an easy mechanism for getting return values back from a thread after it has finished executing. Asynchronous delegate invocations (asynchronous delegates for short) solve this, allowing any number of typed arguments to be passed in both directions. Furthermore, unhandled exceptions on asynchronous delegates are conveniently rethrown on the original thread (or more accurately, the thread that calls EndInvoke), and so they don’t need explicit handling.

Upvotes: 1

Related Questions