Professional Documents
Culture Documents
SP-System Programming
SP-System Programming
SP-System Programming
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.
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.
1. Declare a delegate
2. Set a target method
3. Invoke a delegate
2
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
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)
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);
3
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
Console.WriteLine("IsEven value is {0}",result);
Console.ReadKey();
4
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
}
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);
5
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
MyAction3 ma3 = MethodC;
ma3.Invoke(88);
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;
}
7
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
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;
using System;
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.
To declare an event inside a class, first of all, you must declare a delegate type for the even as:
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);
}
}
}
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);
}
}
11
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 27-28
{
On2DigitNumber.Invoke(number);
}
}
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
}
}
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.
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