Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ThreadStart and Action

Tags:

c#

.net

wpf

Does someone know the difference between

Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
{

and

Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
like image 374
Friend Avatar asked Oct 16 '12 14:10

Friend


People also ask

What is the difference between thread start () and thread run () methods?

Below are some of the differences between the Thread.start () and Thread.run () methods: New Thread creation: When a program calls the start () method, a new thread is created and then the run () method is executed.

What is the difference between a new thread () and task ()?

A new Thread ()is not dealing with Thread pool thread, whereas Task does use thread pool thread. A Task is a higher level concept than Thread.

Why run method does not introduce multithreading in Java?

On other hand in case of direct calling of run method no new thread is created and task is made to be executed on same current thread so only one thread is there and hence no multithreading is introduced.

What is the use of Thread class in Java?

The thread created with the Thread class takes resources like memory for the stack, and CPU overhead for the context switches from one thread to another. The Thread class provides the highest degree of control like the Abort () function, the Suspend () function, the Resume () function, etc.


2 Answers

There should be no difference. ThreadStart and Action are defined as

public delegate void ThreadStart();

public delegate void Action();

i.e., delegate with no parameters and no return value. So they are semantically the same.


However, I would use Action and not ThreadStart, as ThreadStart is strongly associated with Thread constructor, so the code with ThreadStart can hint to direct thread creation and therefore be slightly misleading.

like image 88
Vlad Avatar answered Oct 06 '22 04:10

Vlad


It looks like there is a difference between ThreadStart and Action in the context of BeginInvoke.

They will both run the code within the delegate correctly, as Vlad has mentioned.

However, if an exception occurs within the delegate, ThreadStart results in a TargetInvocationException. But using Action gives you the correct exception from the delegate.

Action should be preferred for this reason.

Have a look at this question.

like image 25
Chris O'Neill Avatar answered Oct 06 '22 03:10

Chris O'Neill