Await and async

I was working on an project that was using the async and await keywords and an college asked what/why use the await/ async keywords when you will still be waiting on the task / thread to finish. Which was an very good question, and the best answer that I could give (of which I am writing it here) is that if you want to start an thread and let it process it’s work whilst still carrying on with the main thread then you would need to write some thread controls etc. But .Net gives you that thread control with the async / await keywords.

The async is short for asynchronous which basically means do something whilst doing something else, e.g. you are able to talk and listen at the same time!.

So what happens is that you can create an method to do some long processing, I am just using an Task delay here to simulate that with also using the await syntax just before it so that it will actually wait for the task delay to finish, as below

 public async Task<Boolean> getCheckAsync(Boolean c)
        {
            System.Console.WriteLine("getCheckAsync about to wait");
            await Task.Delay(1000);
            System.Console.WriteLine("getCheckAsync finished waiting");
            // do some processing.. pulling data from a database / website etc.
            if (c)
                return false;
            else
                return true;
        }

You have to decorate the method call with async Task, since then you will be able to do some await on this method.

The next part is to create an call to this method, and this will start the call as well — start processing the method of getCheckAsync

 Task<Boolean> getCheckAsyncTask = this.getCheckAsync(t);            // calls the process to start processing -- e.g. will output "getCheckAsync about to wait"

And to await for the result, which means that you are able to do some other actions in between the calling the method (getCheckAsync) and waiting on the result.

Boolean res = await getCheckAsyncTask;

So from the full code example below, the first output would be

Calling the async
Waiting for result from getCheckAsync
getCheckAsync about to wait
Bit inbetween the getCheckAsync call

which as you can see has already called the getCheckAsync method and then carried on processing the bit inbetween that is not reliant on the result of the method call (getCheckAsync), but once we are ready for the result of the getCheckAsync method call, the output would carry on with

getCheckAsync finished waiting
Obtainted the result from getCheckAsync
Passed the 'Calling the async'
B = False

Here is the code in full

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace asynctest
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
 
            System.Console.WriteLine("Calling the async ");
 
            Boolean b = p.getCheck(true).Result; 
 
            System.Console.WriteLine("Passed the 'Calling the async'");
            System.Console.WriteLine("B = "+b);
            System.Console.ReadLine();
        }
 
        public async Task<Boolean> getCheck(Boolean t)
        {
            System.Console.WriteLine("Waiting for result from getCheckAsync ");
            Task<Boolean> getCheckAsyncTask = this.getCheckAsync(t);            // calls the process to start processing -- e.g. will output "getCheckAsync about to wait"
            System.Console.WriteLine("Bit inbetween the getCheckAsync call");   // do some extra processing.
            Boolean res = await getCheckAsyncTask;                              // but now we have to "await" for the result.
            System.Console.WriteLine("Obtainted the result from getCheckAsync ");
            return res;
        }
 
        public async Task<Boolean> getCheckAsync(Boolean c)
        {
            System.Console.WriteLine("getCheckAsync about to wait");
            await Task.Delay(1000);
            System.Console.WriteLine("getCheckAsync finished waiting");
            // do some processing.. pulling data from a database / website etc.
            if (c)
                return false;
            else
                return true;
        }
 
    }
}

WFC Soap class within an class communicating with PHP

Within the Windows Foundation Classes you are able to create SOAP end points. These end points you are able to communicate using classes funny enough (because of the WFC being classes). But to communicate with these is fine with PHP and also when you sometimes have a class within an class as a parameter passing to the SOAP end point. Well you are able to do it within PHP as well.

If you have a WFC service and add these to the service for the ServiceContract and create the DataContract’s and DataMembers

[ServiceContract]
public interface IService1
{
    [OperationContract]
    string NewValue(NewName name);
}
 
[DataContract]
public class SecondName
{
    int svalue1;
    int svalue2;
 
    [DataMember]
    public int Svalue1
    {
        get { return svalue1; }
        set { svalue1 = value; }
    }
 
    [DataMember]
    public int Svalue2
    {
        get { return svalue2; }
        set { svalue2 = value; }
    }
}
 
[DataContract]
public class NewName
{
    SecondName secondValue = new SecondName();
 
    [DataMember]
    public SecondName SecondValue
    {
        get { return secondValue; }
        set { secondValue = value; }
    }
}

Created the SecondName class as the second named class with the svalue1/2 within in turn the NewName named class will reference the SecondName class.

And then within the class that implements the interface here is the function name to call within the soap end point called NewValue.

public string NewValue(NewName namesec)
{
    return string.Format("Value : {0}", namesec.SecondValue.Svalue1 + namesec.SecondValue.Svalue2);
}

Well to find out what you need to pass to the soap call I was using an WFC application to write out the debugging information with altering the web.config by

    <system.serviceModel>
      <diagnostics>
        <messageLogging
             logEntireMessage="true"
             logMalformedMessages="false"
             logMessagesAtServiceLevel="true"
             logMessagesAtTransportLevel="false"
             maxMessagesToLog="3000"
             maxSizeOfMessageToLog="2000"/>
      </diagnostics>
    </system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messages"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData="c:\temp\messages.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

which in turns creates a file and in that file there is xml definition what is being sent.

<s:Body>
 <NewValue xmlns="http://tempuri.org/">
 <name xmlns:d4p1="http://schemas.datacontract.org/2004/07/WcfService1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
 <d4p1:SecondValue><d4p1:Svalue1>200</d4p1:Svalue1><d4p1:Svalue2>100</d4p1:Svalue2></d4p1:SecondValue>
 </name>
 </NewValue></s:Body>
</xml>

and within PHP you are able to copy this. but note that the parameter to send is “name” which is not the same as the parameter above (namesec) you have to send to “name” which is what the soap end point is looking for.

class SecondName {
    public $Svalue1;
    public $Svalue2;
}
 
class NewName {
    public $SecondValue;
 
    public function NewName($s1, $s2)
    {
        $this->SecondValue = new SecondName();
        $this->SecondValue->Svalue1 = $s1;
        $this->SecondValue->Svalue2 = $s2;
    }
}
 
$objN = new NewName(200,100);
 
//Create a SOAP client
$client = new SoapClient("http://192.168.0.3/Service1.svc?wsdl");
$retVal = $client->NewValue(array ("name" => $objN));
 
print_r($retVal->NewValueResult);

and the output is

Value : 300

Have attached a file of the project for the WFC webserver and also the php code.

Moonlight

Within kubuntu (or ubuntu derived setups) you can have a moonlight development .. aka the silverlight open source version that will run on linux.

if you install the

monodevelop-moonlight

and also the

monodoc-moonlight-manual

packages, the last one is the manual if you need some help, but the first one will allow the monodevelop development environment have the moonlight plugin which creates a project to develop silverlight applications in.

threads – singleton

As from one of my previous posts about threading in csharp (c#), well with using Singletons you can use similar data between two different threads running.

In basics a singleton is when you want to have a single class instance so that you can share this class so that every time that you use it (even across threads) will only access the same class, it is very useful for when you have a printer spool so that you do not want to have x amount of printer spools (spool is when you have a list of print tasks waiting to print) and thus you only want to have one instance of a printer spool !!.

I have used the singleton creation from Microsoft website, that creates a singleton class that is thread safe which means that I am using the lock method that will lock on a object to stop thread contention and thus only creates a new instance of a Singleton class so that each thread will only get access to a single instance of that class.

So when you want to gain access to that single instance, you just call the

Singleton theSingleton = Singleton.Instance;

So here is the full source code, and below is the output where the output is displaying the value is incrementing otherwise if is was not a singleton class, the main class would print out 0-4 and also the runthismethod would output 0-9 instead!.

using System;
using System.Threading;
 
namespace monotestproject
{
	public sealed class Singleton
	{
		private static int _value;
		private static volatile Singleton instance;
		private static object syncRoot = new Object();
 
		public Singleton() { _value = 0;}
 
		public static Singleton Instance
		{
			get { 
				if (instance == null)
				{
					lock(syncRoot)
					{
						if (instance == null)
							instance = new Singleton();
					}
				}
				return instance;
			}
			private set {}
		}
 
		public int theValue 
		{
			get { return _value;}
			set { _value = value;}
		}
	}
 
	class MainClass
	{
		public static void Main (string[] args)
		{
			Singleton theSingleton = Singleton.Instance;
			// initialize the RunThisMethod as a thread
			Thread theThread = new Thread(RunThisMethod);
			theThread.Start();
 
			for (int j = 0; j < 5; j++)
			{
				theSingleton.theValue++;
				Console.WriteLine("Main Singleton value " + theSingleton.theValue);
				Thread.Sleep(100);
			}
		}
 
		// the method to create as a threadable method
		public static void RunThisMethod()
		{
			Singleton runsSingleton = Singleton.Instance;		
			for (int i =0; i < 10; i++)
			{
				runsSingleton.theValue++;
				Console.WriteLine("RunThisMethod Singleton value " + runsSingleton.theValue);
				Thread.Sleep(45);
			}
		}
	}
}

here is my output, as you can I am getting the singleton value incrementing, which is what should be happening.

Main Singleton value 1
RunThisMethod Singleton value 2
RunThisMethod Singleton value 3
RunThisMethod Singleton value 4
Main Singleton value 5
RunThisMethod Singleton value 6
RunThisMethod Singleton value 7
Main Singleton value 8
RunThisMethod Singleton value 9
RunThisMethod Singleton value 10
Main Singleton value 11
RunThisMethod Singleton value 12
RunThisMethod Singleton value 13
Main Singleton value 14
RunThisMethod Singleton value 15

unsafe – pointers in the code

Sometimes you do miss that pointer part of c++ coding within c#, well you can get around the restriction with using the unsafe syntax which basically means that you are doing some coding that please do not use the restrictions of the virtual machine and just allow direct access to the variable/memory as such.

So the basics is the

// for a block code
unsafe {
code here..
}
// or for the whole method.
public unsafe <returntype> <methodname>
{
}

So to show the code in real code, this will setup a int(eger) value to 50 and then point to the data via a pointer (*) and then you can see that the actual value within the pointer (*) is not the same and also will change every time since the int(eger) value of 50 memory location will most probably be different every time.

using System;
 
namespace unsafetest
{
    class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                int intValue = 50;
                Console.WriteLine("integer value is : " + intValue);
                int* pointerInt = &intValue;
                Console.WriteLine("Pointer to the data is : " + *pointerInt);
                Console.WriteLine("Pointed to the memory value of data is : " + (int)pointerInt);
            }
            Console.ReadLine();
        }
    }
}

the output would be similar to, I am using a (int) cast on the memory location, which since the memory location is very big then it would be better to use something like a hex value output, but this just shows that the value will be different on different runs, if you run it again and again, that will be different values.

integer value is : 50
Pointer to the data is : 50
Pointed to the memory value of data is : 98691076

delegates – settings function on the fly

Delegates allow a virtual method/function (static method) to be called via a link (which is the delegated variable). I have done a post before about delegates but kinder think and also have been asked how do you link one to a class and also change the delegated function due to a user input, so here goes.

I have started with setting up what type of method that I want to be associated with the delegated variable, this will be a mathematical function of either addition or subtraction with using integer values, so we need to return a integer value and also pass in two integer parameters, so a new delegated virtual method would be

public delegate int mathsOp(int value1, int value2);

and here would be a example of a method that the delegate is able to link to, because it takes 2 integer parameters and returns a integer value

public int add(int value1, int value2)
{
	return value1 + value2;
}

so we now have the delegate declaration and also a method to be able to point to, so we now need to setup the variables, one for the actual functions (MathClass that is holding the subtraction and addition methods) and also the delegated variable theMathOp that is a delegated type.

MathClass mathFunc = new MathClass();
 
mathsOp theMathOp;

to actually set the method up on the fly, you just need to tell it where you want the delegated type to point to

theMathOp = new mathsOp(mathFunc.add);

and all is needed to call the delegated type variable, well you just call it like any other method

theMathOp(inputValue1, inputValue2);

that is about it, here is the code in full that will take in some values from the user and also the user is able to choose between addition and subtraction methods

using System;
 
namespace newDelegates
{
	// a maths holding delegated function
	public delegate int mathsOp(int value1, int value2);
 
	class MathClass
	{
		// the functions to call within the class
		public int add(int value1, int value2)
		{
			return value1 + value2;
		}
 
		public int sub(int value1, int value2)
		{
			return value1 - value2;
		}
 
	}
 
	class MainClass
	{
		public static void Main (string[] args)
		{
 
			// setup the maths class which has the functions inside to call
			MathClass mathFunc = new MathClass();
 
			mathsOp theMathOp;
 
			// there is no error checking in the inputs!!
 
			Console.Write("Please enter value 1 : ");
			int inputValue1 = Convert.ToInt16(Console.ReadLine());
			Console.Write("Please enter value 2 : ");
			int inputValue2 = Convert.ToInt16(Console.ReadLine());
 
			Console.WriteLine("Please enter maths function :");
			Console.WriteLine("1 : add");
			Console.WriteLine("2 : sub");
			int mathsInputFun = Convert.ToInt16(Console.ReadLine());
			// setup the virtual function to which ever the user wants
			switch (mathsInputFun)
			{
				case 1 : 
					theMathOp = new mathsOp(mathFunc.add); 
					break;
				case 2 : 
					theMathOp = new mathsOp(mathFunc.sub); 
					break;
				default :
					Console.WriteLine("Settings to add");
					theMathOp = new mathsOp(mathFunc.add); 
					break;
			}
 
			Console.WriteLine("Value 1= " + inputValue1 + (mathsInputFun == 1 ? " + " : " - ") 
			                  + " value 2 = " + inputValue2 + " = ");
 
			// here we call the virtual function that was setup
			Console.WriteLine(theMathOp(inputValue1, inputValue2));
		}
	}
}

and below is the output of two runs of the program, one using addition and the other using subtraction

Please enter value 1 : 3
Please enter value 2 : 2
Please enter maths function :
1 : add
2 : sub
1
Value 1= 3 +  value 2 = 2 = 5
 
second run through
 
Please enter value 1 : 5
Please enter value 2 : 2
Please enter maths function :
1 : add
2 : sub
2
Value 1= 5 -  value 2 = 2 = 3

C# – Console Parameters test

As from my previous post on c++ console parameters, I thought that I would do one with c# (c sharp) as well, just to show the difference in the languages as well.

Compared to c++ where you cannot use the “==” (is equal to) operation because in c++ that is comparing two different memory locations and not the value within the left/right hand variables. Well in c# you can, there is a Equals method as well that you can use, but either or works fine, so in the example code below here is the main part, where I am comparing against a console parameter equalling -h (normally the help)

if (args[i].Equals("-h")) Console.WriteLine("-h option selected(equals)");
if (args[i]=="-h") Console.WriteLine("-h option selected (==)");

both of them are fine to use as you can see from the output at the bottom of the post, both will print out that “-h option selected”, best to use the Equals though.

Here is the full source code

using System;
 
namespace consoletest
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			for (int i = 0; i < args.Length; i++)
			{
				Console.WriteLine("args " + i + " : " + args[i]);								
				if (args[i].Equals("-h")) Console.WriteLine("-h option selected(equals)");
				if (args[i]=="-h") Console.WriteLine("-h option selected (==)");
			}
		}
	}
}

and here is the output using mono as the .Net runtime environment, as you can see both -h has been outputed

mono consoletest.exe -h here
args 0 : -h
-h option selected(equals)
-h option selected (==)
args 1 : here