The best of threading with delegates

How to start a new UI process/thread, passing an object to it?

Context/Scenario:  we need to quickly develop a tool whose target is win7 + on a desktop (users have computers with big screens). We will do that in C# with WPF on Net 4.0.

What do we want to learn?

Using a Delegate method to set the Text of a TextBlock

The core code

private void UpdateText(string text)
	// Set the textbox text.
	tb_Callback.Text = text;
//public delegate void UpdateTextCallback(string text);
public void DelegateMethod(string message)
	try {
		//tb_Callback.Text = message;
		Debug.WriteLine("calling dispatcher");
			new Action(() => {
			           }), null);
		//this.Dispatcher.Invoke(new UpdateTextCallback(this.UpdateText),
		// new object[]{message});
	} catch (Exception exc) {

The threading management

private void NewWindowHandler()
	Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
	newWindowThread.IsBackground = true;

private void ThreadStartingPoint()
	PassingClass passingObj = new PassingClass() {
		FirstPar = "my first par", SecondPar= 123, ThirdPar = DateTime.Now,
		handler = DelegateMethod
	Window1 tempWindow = new Window1(passingObj);
	tempWindow.Closed += (s,e) =>
		Debug.WriteLine("CallBack: " + passingObj.CallBack );

and PassingClass.cs

using System;

namespace SystemAlloc
	public delegate void Del(string message);
	public class PassingClass
		public PassingClass()
		public string FirstPar;
		public int SecondPar;
		public DateTime ThirdPar;
		public string CallBack;
		public Del handler;

3 thoughts on “The best of threading with delegates

  1. Posted a comment about “C# Async and Await Programming Model” here.
    Also, a similar opinion is conveyed in SO: A thread can do many more useful things than Async/Await, but writing code that relies on callbacks is quite difficult and await aims at simplifying it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s