views:

110

answers:

2

This is an Easy Q, but great help:

Under title" Retrieving data from threads MSDN (Here) introduces a way to get data from a child thread by using callback method which is encapsulated by a delegate passed from main thread to the child thread - who has the data.

You can see that clearly ( the last Example in the MSDN page)

My Q is, since we are taking about retrieving data (from child threads to main thread) the call back method should be executed by the main thread and not by the child thread...

I changed the code a bit ( to verify that) so I attached the name of the thread before each output:

 public static void ResultCallback(int lineCount) {
    Console.WriteLine(Thread.CurrentThread.Name + ":Independent task printed {0} lines.", lineCount);  
}

And I named the child thread: "Method2" while the main thread "System"...

I got this output: Method2: Independent task printed 1 lines.

where the correct output should have been : System:Independent task printed 1 lines..

Who is drunk here? MSDN, me or .NET?

A: 

"You" ;-p

Callbacks are still executed on the worker thread; they provide the data back to the calling code - but they don't have an inbuilt way of interrupting the calling thread. It is your code's responsibility to push that work back to the main thread if necessary. For example, in a winforms app you might have:

public static void ResultCallback(int lineCount) {
  // runs on worker thread
  Invoke((MethodInvoker)delegate {
      // runs on UI thread
      Console.WriteLine(Thread.CurrentThread.Name +
         ":Independent task printed {0} lines.", lineCount);
  });
}
Marc Gravell
I got the first partBut didn't get how i puch the work back to the main thread!
Shankarooni
What architecture are you using? winforms? web? wpf? console? service? It varies... with winforms, there is the Control.Invoke (shown above). With WPF/Silverlight, the Dispatcher - etc.
Marc Gravell
I am using console for my thread learning( Hmm that why it underlined the Invoke keyword)
Shankarooni
There is no inbuilt way of doing that with a console exe - your main thread would have to be watching a queue (or similar) to get updates. Of course, being a console exe, it might not matter as much in the first place... (winforms etc have thread affinity; console - not so much).
Marc Gravell
A: 

Hi,

If you don't want/need to use callbacks and the data is fairly small you can always use shared memory and C# lock keyword.

Maciej.

Maciej