SP-System Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Mr. Shahid Jamil email id: shahid@biit.edu.

pk WhatsApp# 0315-5425199
Lecture 27-28

Note:

It is an intimation that following Lectures are not going to repeat and would
be part of mid-term & final exam as well.

(Week 20) Lecture 27-28

Objectives: Learning objectives of this lecture are

 C# - Delegates
 System Defined Delegates
 User Defined Delegates
 Delegates to Named Function
 Delegates to Anonymous Functions
 Delegates to Lambda Expression
 Multicasting Delegates
 C# - Events
 C# - Multi-Threading
 Thread Life Cycle

Text Book & Resources: - Essential LINQ by Charlire Calvert

Here is the YouTube link for the video explanation of the lecture:

1
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28

C3- Delegates
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type
variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates
are implicitly derived from the System.Delegate class. What if we want to pass a function as a
parameter? How does C# handles the callback functions or event handler? The answer is -
delegate.

The delegate defines the method signature that is return type and parameter list types. You can
define variables of delegate, just like other data type, that can refer to any method with the same
signature as the delegate.

There are three steps involved while working with delegates:

1. Declare a delegate
2. Set a target method
3. Invoke a delegate

The following image illustrates the delegate.

2
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28

System Defined Delegates


C# has build delegates name Action and Func. Both are generatic type delegates which has 16 overloaded
version, which means that they can handle fuction having maximum 15 number of input parameter of any
type.

Action delegate handles all type of functions having no return type (i.e. void)

Func delegate handles all type of fuctions having any kind of return type (i.e. other than void)

Below are few examples to explain Action and Func

static void Main(string[] args)


{
// calling void type fucntions

//assigning Function to Delegate


Action a1 = MethodA;
//calling function via Delegate using invoke.
Console.WriteLine("Call style-1");
a1.Invoke();
//OR you can also use the below style
Console.WriteLine("Call style-2");
a1();// same as above

Action<string> a2 = MethodB;
a2.Invoke("Hello Delegate-Call 1");
// OR
a2("Hello Delegate-Call 2");

Action<int> a3 = MethodC;
a3.Invoke(99);

Action<double> a4 = MethodD;
a4(6.9012);

Action<float, int> a5 = MethodE;


a5.Invoke(3.92f, 25);

//Now calling functions having return types


Func<int> f1 = GetRandom;
int ans = f1.Invoke();
Console.WriteLine("GetRandom value is {0}",ans);

Func<int, int> f2 = Square;


int sqr = f2(ans);
Console.WriteLine("Square value is {0}",sqr);

Func<float, int, float> f3 = Percentage;


float percent = f3.Invoke(88.5f, 100);
Console.WriteLine("Percentage value is {0}", percent);

Func<int, bool> f4 = IsEven;


bool result = f4.Invoke(89);

3
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
Console.WriteLine("IsEven value is {0}",result);

Func<float, float, bool> f5 = IsEqual;


bool result1 = f5(12.3f, 12.30f);
Console.WriteLine("IsEqual value is {0}",result1);

Console.ReadKey();

static void MethodA()


{
Console.WriteLine("This is Method-A");
}
static void MethodB(string msg)
{
Console.WriteLine("This is Method-B with String input-{0}",msg);
}

static void MethodC(int data)


{
Console.WriteLine("This is Method-C with Int32 input-{0}", data);
}

static void MethodD(double data)


{
Console.WriteLine("This is Method-D with Double input-{0}", data);
}
static void MethodE(float gpa,int age)
{
Console.WriteLine("This is Method-E with float, int input-{0},{1}", gpa,age);
}

/// following fuctions having return types


///

static int GetRandom()


{
Console.WriteLine("Get Random called");
return new Random().Next(1, 20);
}

static int Square(int b)


{
Console.WriteLine("Square with input-{0}",b);
return b * b;
}

static float Percentage(float obtained,int total)


{
Console.WriteLine("Quotient with input-{0},{1}",obtained,total);
return (obtained*100.0f)/total;
}

static bool IsEven(int data)


{
Console.WriteLine("IsEven with input-{0}",data);
return data % 2 == 0;

4
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
}

static bool IsEqual(float f1, float f2)


{
Console.WriteLine("IsEqual with input-{0},{1}",f1,f2);
return f1 == f2;
}

User Defined Delegates


User can also declare his/her own delegate. It can be either generic or non-generic. Following are two
type of user defined delegates. First which will handle void return type functions and second is for other
than void type.

User defined delegate handling void return type functions:

public delegate void MyAction1();


public delegate void MyAction2(string s);
public delegate void MyAction3(int d);
public delegate void MyAction4(float f,int d);

User defined delegate handling other than void return type functions:
public delegate int MyFunc1();
public delegate int MyFunc2(int d);
public delegate float MyFunc3(float f,int d);
public delegate bool MyFunc4(int d);

Below is the complete example code for explaination:

public delegate void MyAction1();


public delegate void MyAction2(string s);
public delegate void MyAction3(int d);
public delegate void MyAction4(float f,int d);

public delegate int MyFunc1();


public delegate int MyFunc2(int d);
public delegate float MyFunc3(float f,int d);
public delegate bool MyFunc4(int d);
class Program
{
static void Main(string[] args)
{
///User defined delegates
///Non - Generic
///

MyAction1 ma1 = MethodA;


ma1.Invoke();//

MyAction2 ma2 = MethodB;


ma2.Invoke("Hello User Defined Non-Generic");

5
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
MyAction3 ma3 = MethodC;
ma3.Invoke(88);

MyAction4 ma4 = MethodE;


ma4(88.7f, 334);

MyFunc1 mf1 = GetRandom;


int ans1 = mf1.Invoke();
Console.WriteLine("GetRandom call {0}",ans1);

MyFunc2 mf2 = Square;


int ans2 = mf2(20);
Console.WriteLine("Square call {0}",ans2);
Console.ReadKey();
}

static void MethodA()


{
Console.WriteLine("This is Method-A");
}
static void MethodB(string msg)
{
Console.WriteLine("This is Method-B with String input-{0}",msg);
}

static void MethodC(int data)


{
Console.WriteLine("This is Method-C with Int32 input-{0}", data);
}

static void MethodD(double data)


{
Console.WriteLine("This is Method-D with Double input-{0}", data);
}
static void MethodE(float gpa,int age)
{
Console.WriteLine("This is Method-E with float, int input-{0},{1}", gpa,age);
}

/// following fuctions having return types


///

static int GetRandom()


{
Console.WriteLine("Get Random called");
return new Random().Next(1, 20);
}

static int Square(int b)


{
Console.WriteLine("Square with input-{0}",b);
return b * b;
}

static float Percentage(float obtained,int total)


{

6
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
Console.WriteLine("Quotient with input-{0},{1}",obtained,total);
return (obtained*100.0f)/total;
}

static bool IsEven(int data)


{
Console.WriteLine("IsEven with input-{0}",data);
return data % 2 == 0;
}

static bool IsEqual(float f1, float f2)


{
Console.WriteLine("IsEqual with input-{0},{1}",f1,f2);
return f1 == f2;
}
}

Delegates to Named Function


Above examples show how to call named functions via delegates. Here is the code stuff for named
function call.

This is System defined delegate example:

//assigning Function to Delegate


Action a1 = MethodA;
//calling function via Delegate using invoke.
a1.Invoke();

//Now calling functions having return types


Func<int> f1 = GetRandom;
int ans = f1.Invoke();

This is now user defined non-generic delegate example:

public delegate void MyAction2(string s);//declaration

MyAction2 ma2 = MethodB; // assignment


ma2.Invoke("Hello User Defined Non-Generic");//Calling

MyFunc1 mf1 = GetRandom;


int ans1 = mf1.Invoke();
Console.WriteLine("GetRandom call {0}",ans1);

Delegates to Anonymous Functions


C# supports nameless functions, called anonymous functions. Here is the code stuff to explain:

//delegates for anonymous functions


Action a11 = delegate () {
Console.WriteLine("this is anonymous function-1");
};
a11.Invoke();

7
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28

Action<int> a12 = delegate (int x) {


Console.WriteLine("this is anonymous function-2");
Console.WriteLine("here is input-{0}",x);
};
a12.Invoke(34);

MyFunc2 mf12 = delegate (int x) {


Console.WriteLine("this is anonymous function-2");
Console.WriteLine("here is input-{0}", x);
return x * x;
};
int ans3 = mf12.Invoke(34);

Delegates to Lambda Expression


Delegates also support lambda expression, here is the code example:

Action<int, float> a22 = (d,ff) => { Console.WriteLine("int is {0},float is",d,ff);};


a22.Invoke(45, 56.5f);

Func<int, bool> f22 = x => { Console.WriteLine("input -{0}",x); return x % 2


== 0; };
bool result22 = f22.Invoke(34);
Console.WriteLine("result is [0}",result22);

Multicasting Delegates
The delegate can point to multiple methods. A delegate that points multiple methods is called a multicast
delegate. The "+" or "+=" operator adds a function to the invocation list, and the "-" and "-=" operator
removes it.

Action<int> aa = PrintSquare;
aa += PrintCube;
aa += PrintIsEven;

Console.WriteLine("call with three functions for 3");


aa.Invoke(3);

//now remove the function


aa -= PrintCube;

Console.WriteLine("call with two functions for 5");


aa.Invoke(5);

Here is the complete code stuff to run:

using System;

delegate int NumberChanger(int n);


namespace DelegateAppl {
class TestDelegate {
static int num = 10;
8
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28

public static int AddNum(int p) {


num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

nc = nc1;
nc += nc2;

//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

C# - Events
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as
system generated notifications. Applications need to respond to events when they occur. For example,
interrupts. Events are used for inter-process communication.

The events are declared and raised in a class and associated with the event handlers using delegates within
the same class or some other class. The class containing the event is used to publish the event. This is
called the publisher class. Some other class that accepts this event is called the subscriber class. Events
use the publisher-subscriber model.

A publisher is an object that contains the definition of the event and the delegate. The event-delegate
association is also defined in this object. A publisher class object invokes the event and it is notified to
other objects.

9
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28

A subscriber is an object that accepts the event and provides an event handler. The delegate in the
publisher class invokes the method (event handler) of the subscriber class.

Following figure will illustrate the events in C#.

To declare an event inside a class, first of all, you must declare a delegate type for the even as:

public delegate string MyDel(string str);


then, declare the event using the event keyword −

event MyDel MyEvent;


The preceding code defines a delegate named MyDel and an event named MyEvent, which invokes the
delegate when it is raised.

Here is example code:

using System;

namespace EventDemo
{
public delegate string MyDel(string str);
class EventProgram
{
event MyDel MyEvent;
public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username)
{
return "Welcome " + username;
}
static void Main(string[] args)
{
EventProgram obj1 = new EventProgram();

10
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
string result = obj1.MyEvent("Abdul Quddos");
Console.WriteLine(result);
}

}
}

Here is another example


using System;

namespace EventDemo
{
public delegate void NumberDelegate(int number);
class RandomNumberGeneration
{
public event NumberDelegate OnEvenNumber;
public event NumberDelegate OnOddNumber;
public event NumberDelegate On1DigitNumber;
public event NumberDelegate On2DigitNumber;
public event NumberDelegate On3DigitNumber;
public void GenerateNumbers()
{
Random rd = new Random();
for(int counter=1;counter<=50;counter++)
{
System.Threading.Thread.Sleep(1000);
var number = rd.Next(1, 1000);
if(number % 2 == 0)
{
//number is even
if (OnEvenNumber != null)
{
OnEvenNumber.Invoke(number);
}
}

if (number % 2 != 0)
{
//number is odd
if (OnOddNumber != null)
{
OnOddNumber.Invoke(number);
}
}

if (number >= 1 && number <= 9)


{
//number is of 1 Digit
if (On1DigitNumber != null)
{
On1DigitNumber.Invoke(number);
}
}

if (number>=10 && number <= 99)


{
//number is of 2 Digit
if (On2DigitNumber != null)

11
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
{
On2DigitNumber.Invoke(number);
}
}

if (number >= 100 && number <= 999)


{
//number is of 3 Digit
if (On3DigitNumber != null)
{
On3DigitNumber.Invoke(number);
}
}
}
}
}
}

How to call in main

using System;

namespace EventDemo
{
class EventProgram
{
static void Main(string[] args)
{
RandomNumberGeneration rng = new RandomNumberGeneration();
// rng.OnEvenNumber += HandleEvens;
rng.OnOddNumber += HandleOdds;
rng.On3DigitNumber += Handle3Digits;
rng.GenerateNumbers();//generate 50 random numbers, range 1-1000

static void HandleEvens(int no)


{
//your logic here
//i want to save this no in db.
}

static void HandleOdds(int no)


{
//your logic here
}

static void Handle3Digits(int no)


{
//your logic here
}

}
}

12
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28

C# - Multi-Threading
A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If
your application involves complicated and time consuming operations, then it is often helpful to set
different execution paths or threads, with each thread performing a particular job.

Threads are lightweight processes. One common example of use of thread is implementation of
concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and
increase efficiency of an application.

So far we wrote the programs where a single thread runs as a single process which is the running instance
of the application. However, this way the application can perform one job at a time. To make it execute
more than one task at a time, it could be divided into smaller threads.

Thread Life Cycle


The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends
when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread −
 The Unstarted State − It is the situation when the instance of the thread is created but the Start
method is not called.
 The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle.
 The Not Runnable State − A thread is not executable, when
o Sleep method has been called
o Wait method has been called
o Blocked by I/O operations
 The Dead State − It is the situation when the thread completes execution or is aborted.

In C#, the System.Threading.Thread class is used for working with threads. It allows creating and
accessing individual threads in a multithreaded application. The first thread to be executed in a process
is called the main thread.
When a C# program starts execution, the main thread is automatically created. The threads created using
the Thread class are called the child threads of the main thread. You can access a thread using
the CurrentThread property of the Thread class.

13

You might also like