Threading – running different parts of the program at “once”

A thread is when you “spawn” off another process (a process is like another program running within itself).

The operating system gives the impression that it is running allot of programs at the same time, but what is happening that allot of processes (programs) have access to the CPU for a limited amount of time, e.g. 10 milliseconds, and then leave the CPU execution stage whilst another process will enter there CPU execution stage (this is the part where the program is actually doing something).

To start with lets first create a method that is run within new thread, here we are just going to output a message and sleep for a bit, loop this over for 10 times.

// the method to create as a threadable method
public static void RunThisMethod()
{
	for (int i =0; i < 10; i++)
	{
		Console.WriteLine("RunThisMethod number : "+i.ToString() + " Sleep for 45");
		Thread.Sleep(45);
	}
}

Now lets create a thread, since a Thread has to be a delegated method but with .net 2 and above the .net environment will pick the correct delegate for you, so this means that you can just pass in the method name to the Thread class and that is it

	Thread theThread = new Thread(RunThisMethod);

To start the new Thread, it is as easy as start

	theThread.Start();

Here is the full source code, for demoing how the main and the runMyMethod flip between each other (e.g. each process has time in the processor(s) to run)

using System;
using System.Threading;
 
namespace myThread
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			// initialize the RunThisMethod as a thread
			Thread theThread = new Thread(RunThisMethod);
			theThread.Start();
 
			for (int j = 0; j < 5; j++)
			{
				Console.WriteLine("Main method number : "+j.ToString()+" Sleep for 100");
				Thread.Sleep(100);
			}
		}
 
		// the method to create as a threadable method
		public static void RunThisMethod()
		{
			for (int i =0; i < 10; i++)
			{
				Console.WriteLine("RunThisMethod number : "+i.ToString() + " Sleep for 45");
				Thread.Sleep(45);
			}
		}
	}
}

and here would be the output

Main method number : 0 Sleep for 100
RunThisMethod number : 0 Sleep for 45
RunThisMethod number : 1 Sleep for 45
RunThisMethod number : 2 Sleep for 45
Main method number : 1 Sleep for 100
RunThisMethod number : 3 Sleep for 45
RunThisMethod number : 4 Sleep for 45
Main method number : 2 Sleep for 100
RunThisMethod number : 5 Sleep for 45
RunThisMethod number : 6 Sleep for 45
Main method number : 3 Sleep for 100
RunThisMethod number : 7 Sleep for 45
RunThisMethod number : 8 Sleep for 45
Main method number : 4 Sleep for 100
RunThisMethod number : 9 Sleep for 45

loading images on the fly

To load a image from the server, local or remote depending if you are developing locally. I have been using monodevelop with the moonlight addin, this allows you to create silverlight applications with Linux :).

To start with, if you create a new solution by going to File->New->Solution and then selecting the moonlight Application project as similar to creating any other new project within monodeveloper (or within visual studio if you are using visual studio to create this silver light loading images on the fly).

Moonlight mono-develop project setup

And then within your main page.xaml file you need to define where you want the image to be placed.

		<Image x:Name="Image1" Source="dot.jpeg"></Image>
		<Button x:Name="Button1" Click="ButtonClick" Height="50" Content="Click" ></Button>

above also includes the Button that you are going to click onto to load the image, in this case it will call the ButtonClick function (from the above it is the “click” method). The ButtonClick is behind the page.xaml within the page.xaml.cs file (the csharp file).

So once that button has been clicked it will call this function

		public void ButtonClick(System.Object sender,System.EventArgs eventy)
		{
			System.Windows.MessageBox.Show("hi there");
			Image1.Source = new BitmapImage(new Uri("lcd.png", UriKind.Relative));
		}

I put a little message pop up window to say “hi there”, just so that you know it have been clicked encase the lcd.png (as taken from the open clip art website here) is not in the correct place, in this case it is placed within the bin/debug, but if you are using a release edition or using visual studio you may have somewhere else.

I have included the full source code and image within a zip file above, please feel free to download.

Here is the full page.xaml if you want to look over it.

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             Width="500" Height="350"
             x:Class="moonlighttest.Page"
>
	<Grid x:Name="LayoutRoot" Background="Black">
		<Image x:Name="Image1" Source="dot.jpeg"></Image>
		<Button x:Name="Button1" Click="ButtonClick" Height="50" Content="Click" ></Button>
	</Grid>
</UserControl>

and here is the full page.xaml.cs file.

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
 
namespace moonlighttest
{
 
	public partial class Page : UserControl
	{
 
		public Page ()
		{
			this.InitializeComponent ();
		}
 
		public void ButtonClick(System.Object sender,System.EventArgs eventy)
		{
			System.Windows.MessageBox.Show("hi there");
 
			Image1.Source = new BitmapImage(new Uri("lcd.png", UriKind.Relative));
		}
	}
 
}

Web service – the consumer (client)

As from the web service server from the previous post you can now link to that web service. You will need to do a couple of things to be able to get the client to “talk” to the web service.

To start with on the server part of the tutorial you will need to create the dll (dynamically linked library) for the FirstWebService of the server, this is because this is what the client will use to “talk” to the server. To create this dll file you will need to compile up the FirstWebService, pull information from the server about the service and then just compile into a library

I am using mono, so if you are using .net within Windows then there is a similar command (may be just wsdl instead of wsdl2)

wsdl2 http://localhost/csharp/web_service.asmx?WSDL
 
--- output from the above command
Web Services Description Language Utility
Mono Framework v2.0.50727.1433
Writing file 'FirstWebService.cs'

as you can see it has created a file called FirstWebService.cs, a csharp source file of the WSDL (Web Services Description Language). To compile this into a FirstWebService.dll within the mono environment you just need to

gmcs /t:library FirstWebService.cs -r:System.Web.Services

the /t:library means to create a .dll file, if you do not pass in the “-r:System.Web.Services” it will complain with the below error.

FirstWebService.cs(21,51): error CS0234: The type or namespace name `Services' does not exist in the namespace `System.Web'. Are you missing an assembly reference?
Compilation failed: 1 error(s), 0 warnings

if you place the FirstWebService.dll within a bin directory within the directory where you are hosting the client from (you may need to create the bin directory for the dll)

Now it is the consumer (the client)

Since we have a FirstWebService.dll within the bin, this means that we try to compile up the client (on-the-fly) it knows how to create the class of FirstWebService. So to call the function of “Add” on the web service, we just need to create a new class of type FirstWebService and then call that function (and the rest is done behind the scenes)

    FirstWebService myFirstWebService = new FirstWebService();
    myFirstWebService.Add(4,5);

that is about it, of course it is nicer to have a web page to post some values to the server from the client, so here is the client source code, if you save this as web_service_consumer.aspx (aspx is a web page extension) and then just goto that web page hosted on the apache environment.

<%@ Page Language="C#" %>
<script runat="server">
// on the asp:Button onclick call this method
void runWebService_Click(Object sender, EventArgs e)
{
    FirstWebService myFirstWebService = new FirstWebService();
    // call the add method from the webservice
    // pass in the 2 values from the page and convert to integer values
    resultLabel.Text = myFirstWebService.Add(
		  Int32.Parse(number1.Text),
                  Int32.Parse(number2.Text)).ToString();
}
</script>
<html>
<head>
<title>ASP Web service consumer</title>
</head>
<body>
<form runat="server">
      First Number to Add : <asp:TextBox id="number1" runat="server">0</asp:TextBox>
<br/>
      Second Number To Add :
      <asp:TextBox id="number2" runat="server">0</asp:TextBox>
<br/>
      THE WEB SERVICE RESULTS!!!
<br/>
      Adding result : <asp:Label id="resultLabel" runat="server">Result</asp:Label>
<br/>
      <asp:Button id="runService" onclick="runWebService_Click" runat="server" Text="Run the Service"></asp:Button>
</form>
</body>
</html>

when you goto that page and see a error like

The type or namespace name `FirstWebService' could not be found. Are you missing a using directive or an assembly reference?
 
Source Error:
 
Line 4: void runWebService_Click(Object sender, EventArgs e)
Line 5: {
Line 6:     FirstWebService myFirstWebService = new FirstWebService();

that is because you have not created the bin directory and placed the FirstWebService.dll into that directory as describe at the top of this page.

Web service

An web service is basically like a SOAP server in that it “talks” from the client-server in XML with the client requesting the function on the server and obtaining a result.

I am using mono to compile and run the web service since I am running apache on Linux (kubuntu) (here is how I setup the mono apache module within k/ubuntu).

To start with, you need to create a web service instance and what language you are going to be using (since using mono then c#) and also the class that you want to “expose” to the web service itself.

<%@ WebService language="C#" class="FirstWebService" %>

after that you then need to add the attribute to the class to tell the compiler that the class is going to be a webservice and what the base directory is going to be (I created a new directory within the apache hosting directory), since we are writing a WebService we need to inherit from a System.Web.Services.WebService

[WebService(Namespace="http://localhost/csharp/")]
public class FirstWebService : WebService

and then just within the class structure you only need to tell the function with a attribute heading of [WebMethod] that it is going to be “exposed” to the web service, if you do not put that in, it will be “exposed” to the web service and thus the client cannot access that method.

    [WebMethod]
    public int Add(int a, int b)

and that is about it, the mono (and of course .net base framework) will create the rest of the WSDL and additional parts for a WebService.

Here is the full web service code in full, save this as web_service.asmx (the asmx means a web service extension)

<%@ WebService language="C#" class="FirstWebService" %>
 
using System;
using System.Web.Services;
 
// expose as the web service
[WebService(Namespace="http://localhost/csharp/")]
public class FirstWebService : WebService
{
    // expose as a web method
    [WebMethod]
    public int Add(int a, int b)
    {
        return TheAddingMethod(a,b);
    }
 
    // this one will not be exposed since it does not have the [WebMethod] attribute
    public int TheAddingMethod(int a, int b)
    {
	// but since it is part of the class you can still call class methods etc.
	return a+b;
    }
}

and when you goto the web URL for the webservice you should see something similar to this

The FirstWebService URL
The FirstWebService URL

if you click on the left menu “add” and then “test form” to test the webservice, it will bring up a window similar to the below, I have done a full test with adding 4 + 5 = 9

Testing the first web service
Testing the first web service

Mono – web development on Linux

It is really easy to get some web c# (csharp) (asp.net) development within a Linux setup, since I use kubuntu which is derived from ubuntu. All you need to do is to

this installs the mono module for the apache2

aptitude install libapache2-mod-mono

to enable the module to work within apache2 you have to update the mods-enabled directory and to do this, just use the

a2enmod mod_mono_auto

which stands for apache2 (a2) enable (en) mod (module) and then the module name, you will need to restart apache2 for it to work

/etc/init.d/apache2 restart

that is it., then if you look within the /etc/apache2/mods-enabled you will notice the

mod_mono_auto.conf
mod_mono_auto.load

of course you could symlink them yourself, but it is just easier to use the a2enmod script.

Within the .conf file it tells apache what extensions to “listen” to direct to the module mono instead of either php module or just a static html web page.

To test the setup, just create a directory within your hosting directory this is normally /var/www/ or just place a file in that base directory /var/www it is up to you, but within that file you could create a basic test file like.

<%@ Page Language="C#" %>
<html>
  <head>
    <title>Apache2 Mod mono test page</title>
  </head>
  <body>
        <form id="form1" runat="server">
          <asp:label id="lbl1" runat="server">Apache2 Mod mono test page</asp:label>
        </form>
  </body>
</html>

the asp:label will be the main test, since that part of the csharp library as such. you should see something like

Apache2 Mod mono test page

Events – fire that event

An event will be fired when something has happened and then you can link to that event and do something else if you wanted to. To start of with you have to link a event with a delegate function which will be the event handler.

To setup a delegate you can have the object and also any event arguments ( you can add in more if you want to, but these are the basics to include)

	// setup a delegate for the event to fire with.
	public delegate void ChangedEventHandler(object sender, EventArgs e);

here is the class that will actual fire the event, to start with I link the “event” to a virtual method as such called Changed (with the delegate from above ChangedEventHander).

	// this is the MyEvent class that will create the event fired.
	public class MyEvent 
	{
		private int x;
 
		// the event for this internal class
		public event ChangedEventHandler Changed;

here is the event firing function, this will call the Changed “virtual” method as such when ever you call this function.

		protected virtual void ThisHasChanged(EventArgs e)
		{
			// try and call the delegate ChangedEventHandler
			// make sure that there is something to call for the event to fire.
			if (Changed != null)
				Changed(this, e);
		}

and here is the get/set for the internal X variable and in the set I call the ThisHasChanged function above.

		// call the ThisHasChanged event when you set the internal value of X.
		public int xValue
		{
			get { return x;}
			set { x = value;ThisHasChanged(EventArgs.Empty); }
		}
	}

So that is the event firing, but you will need to have a listener that will listen to any events and call something that will deal with the fired event, so here is the listener class.

So the listener, is just like any other class, but you will need to have a internal reference to the class above so that you can link to the event fired, so here is the MyEvent internal class for the listener.

	// the listener for the event firing
	class EventListener
	{
		// MyEvent class
		private MyEvent ThisIsMyEvent;

and then the constructor for the EventListener, you pass in the MyEvent class that you want to “link” (the one that you will create within the running part of the program). and from within the MyEvent, there was a “virtual” method as such called “Changed”, well now we can create a link so that when that event “Changed” has been called from within the MyEvent Class I can link to a function within this class EventListener with using a new delegate ChangedEventHandler and the ValueHadChanged is within the EventListener class.

		// the class constructor and you need to pass the MyEvent class to link to the listener.
		public EventListener(MyEvent SetUpTheEventLink)
		{
			// Create a link to the MyEvent class passed in to the internal MyEvent Class
			ThisIsMyEvent = SetUpTheEventLink;
			// this is the link to the listern function.
			ThisIsMyEvent.Changed += new ChangedEventHandler(ValueHadChange);
		}

here is the ValueHadChange, same setup as the delegate parameters since we are basically passing event details between them both and can pass in more details is you want to, but you really only want to have the object (the MyEvent class) and any event arguments e.g. errors etc. at present it just says , “Oh yeah.. I have altered”.

		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
		}

since there was a Changed link attached to the above function, to clean up you can detach the link with using something similar to the constructor of this class, but instead of using += (to add) you just need to subtract from the Change virtual method -=

		// detach the listener function from the event MyEvent 
		public void Detach()
		{
			// take the event linked from the MyEvent class.
			ThisIsMyEvent.Changed -= new ChangedEventHandler(ValueHadChange);
			ThisIsMyEvent = null;
		}
	}

Here is the full code

using System;
 
// when alter a number in the internal part of the class.
namespace codingfriendsEvents
{
	// setup a delegate for the event to fire with.
	public delegate void ChangedEventHandler(object sender, EventArgs e);
 
	// this is the MyEvent class that will create the event fired.
	public class MyEvent 
	{
		// the event for this internal class
		public event ChangedEventHandler Changed;
 
		private int x;
 
		protected virtual void ThisHasChanged(EventArgs e)
		{
			// try and call the delegate ChangedEventHandler
			// make sure that there is something to call for the event to fire.
			if (Changed != null)
				Changed(this, e);
		}
 
		// call the ThisHasChanged event when you set the internal value of X.
		public int xValue
		{
			get { return x;}
			set { x = value;ThisHasChanged(EventArgs.Empty); }
		}
	}
 
	// the listener for the event firing
	class EventListener
	{
		// MyEvent class
		private MyEvent ThisIsMyEvent;
 
		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
		}
 
		// the class constructor and you need to pass the MyEvent class to link to the listener.
		public EventListener(MyEvent SetUpTheEventLink)
		{
			// Create a link to the MyEvent class passed in to the internal MyEvent Class
			ThisIsMyEvent = SetUpTheEventLink;
			// this is the link to the listern function.
			ThisIsMyEvent.Changed += new ChangedEventHandler(ValueHadChange);
		}
 
		// detach the listener function from the event MyEvent 
		public void Detach()
		{
			// take the event linked from the MyEvent class.
			ThisIsMyEvent.Changed -= new ChangedEventHandler(ValueHadChange);
			ThisIsMyEvent = null;
		}
	}
 
	class TestMyEvent
	{
		public static void Main()
		{
			// create a new MyEvent class
			MyEvent MyEventToCheck = new MyEvent();
 
			// link in with the EventLister , passing in the class of MyEvent
			EventListener TheListener = new EventListener(MyEventToCheck);
 
			// should fire of a event !! because I am changing the internal x value.
			MyEventToCheck.xValue = 10;
 
			// will not fire a event because I have not changed it.
			Console.WriteLine("X = " + MyEventToCheck.xValue);
 
			// will fire of another event.
			MyEventToCheck.xValue = 5;
 
			TheListener.Detach();
		}
	}
}

and here would be the output

Oh yeah.. I have been altered
X = 10
Oh yeah.. I have been altered

If you want to gain access to the object sender within the EventListener class to the function that was listening to the event fired, if you alter it as below, but also since because the MyEvent was also linked within the constructor you also have that link as well.

		// same style as the delegate e.g. object, eventargs, that is sent from the event fired.
		// THIS IS THE LISTERN as such, function..if you want to do something like.. do not alter the value!! 
		private void ValueHadChange(object sender, EventArgs e)
		{
			Console.WriteLine("Oh yeah.. I have been altered");
			Console.WriteLine("New value of X = " + ((MyEvent)sender).xValue);
			Console.WriteLine("Internal MyEvent class x = " + ThisIsMyEvent.xValue);
		}

then you can gain access to the MyEvent from within the object sender and the output would be

Oh yeah.. I have been altered
New value of X = 10
Internal MyEvent class x = 10
X = 10
Oh yeah.. I have been altered
New value of X = 5
Internal MyEvent class x = 5

Equals why ? and why not ==

In Object oriented programming languages, there is a nice keyword that is “new” what this does is create a new instance of a object and run the objects constructor method and setup up the internal variables, for example.

class classA 
{
	private int x;
 	public	classA() { x= 0;}
	public	classA(int value) { x = value;}
}
...
classA a = new classA();

this will create a new instance of A with the constructor (same name as the class) setting x equal to 0. What is happening is that the variable “a” is pointing to a memory location of the newly created object on the memory heap for example.

Local variables

Object Memory location / value
a 0x0102

which the 0x0102 memory location is pointing to a newly constructed classA space

Memory location Object values
0x0102 classA – a instance over head (garage collection etc)
0x0104 x value 0

There is over head details associated with the classA (a instance) for the garage collection/polymorphism for example. So the actual “a” variable is just pointing to this place in memory, if you created a new classA instance then another place in memory will be created, for example lets create classA a2 as

classA a2 = new classA();

and now a example of the memory locations / values would be similar to

Local variables

Object Memory location / value
a 0x0102
a2 0x0108

with the memory heap as such.

Memory location Object values
0x0102 classA – a instance over head (garage collection etc)
0x0104 x value 0
0x0108 classA – a2 instance over head (garage collection etc)
0x010a x value 0

so you would have thought that if you did,

if (a == a2)

then they would be equal, since both have a value of 0 ? well this is not the case, since the == is just comparing the value within the variable and thus the a = 0x0102 and a2 = 0x0108 which are not equal. To compare two different instances of a class you need to override the Equals function within the class (all classes are derived from object class)

So the code would be

		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}

and now you can compare the two classA instances with

if (a.Equals(a2))

since the Equals function is actually comparing the values within the class instance and not the a/a2 variable values (which point to memory locations).

Here is the full code

using System;
 
namespace equaltest
{
	class classA 
	{
		private int x;
	 	public	classA() { x= 0;}
		public	classA(int value) { x = value;}
 
		public int xValue {
			get { return x;}
			set { x = value;}
		}
 
		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			classA a = new classA();
			a.xValue = 10;
			Console.WriteLine("A x value = " + a.xValue);
 
			classA a2 = new classA();
			a2.xValue = 10;
			Console.WriteLine("A2 x value = " +a2.xValue);
			//so they are the same in x values, but are they the same !! ==
 
			if (a == a2)
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
			// of course they are NOT the same value, because the equals is comparing there actual object values
			// and not there x value inside them, and with the "new" keyword they are both pointing to different 
			// places on the heap of storage, thus they are NOT the same..
			// a may equal heap storage = 0x1010
			// a2 may equal heap storage= 0x1020
			// both have the same x value but different memory location values.
 
			// but implementing a Eqauls comparsion function you can compare the two variables internals 
			// as you see fit.
			if (a.Equals(a2))
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
		}
	}
}

and the output would be

A x value = 10
A2 x value = 10
a does not equal a2
a does equal a2

since I am overriding the Equals from the base object class, the compiler may warn that I am not overriding the GetHaseCode(), but that is k for this example.

Example of the compiler warning message

Description=`equaltest.classA' overrides Object.Equals(object) but does not override Object.GetHashCode()(CS0659)]