1

If you create a ThreadStart delegate you can call the function Invoke() from it, but I tried search through documentation and I was not able to find the Invoke() function and what exactly it does, I'm wondering, does it creates a new thread and executes the function delegated to it, or it just executes as an action on the same thread ?

Edit 1:

sample code:

ThreadStart threadStart = delegate
{
   someFunction();
}

threadStart.Invoke();
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
khofez
  • 65
  • 1
  • 8

2 Answers2

3

No, it does not create a new thread. It is just a delegate that has a certain shape - no parameters or return value - which a Thread takes in its constructor.

Invoke here will just simply call the method.

For instance, the ManagedThreadId is the same in this example:

using System;
using System.Threading;             

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        ThreadStart s = () => Console.WriteLine("In s: {0}", Thread.CurrentThread.ManagedThreadId);

        Console.WriteLine("Before s.Invoke: {0}", Thread.CurrentThread.ManagedThreadId);

        s.Invoke();

        Console.WriteLine("After s.Invoke: {0}", Thread.CurrentThread.ManagedThreadId);
    }
}

https://dotnetfiddle.net/9TrDiZ

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Have a play with this code:

ThreadStart x = () => Console.WriteLine("A" + Thread.CurrentThread.ManagedThreadId);

Console.WriteLine("B" + Thread.CurrentThread.ManagedThreadId);
x();
x.Invoke();
x.BeginInvoke((AsyncCallback)(z => Console.WriteLine("C" + Thread.CurrentThread.ManagedThreadId)), null);

You'll get results like this:

B11
A11
A11
A8
C8

That should help you to figure out what's going on.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Well, so the "BeginInvoke" calls the ThreadStart function and calls that function callback after it, both on a parallel thread? – khofez Feb 20 '18 at 16:05