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");
		tb_Callback.Dispatcher.BeginInvoke(
			new Action(() => {
			           	this.UpdateText(message);
			           }), null);
		//this.Dispatcher.Invoke(new UpdateTextCallback(this.UpdateText),
		// new object[]{message});
		
	} catch (Exception exc) {
		Debug.WriteLine(exc.Message);
		Debug.WriteLine(exc.StackTrace);
	}
}

The threading management

private void NewWindowHandler()
{
	Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
	newWindowThread.SetApartmentState(ApartmentState.STA);
	newWindowThread.IsBackground = true;
	newWindowThread.Start();
}

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 );
		passingObj.handler(passingObj.CallBack);
		Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
	};
	tempWindow.Show();
	System.Windows.Threading.Dispatcher.Run();
}

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;
	}
}
Advertisements

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.

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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