The document discusses several advanced programming topics including multithreaded applications, delegates, inheritance, and interfaces in C#. It provides examples of creating and running multithreaded applications using the Thread class. It also demonstrates how to use delegates to reference and call methods indirectly, and how to handle thread synchronization issues in multithreaded programs. The document explains inheritance in C# and compares overriding and hiding. It defines what interfaces are and how they allow for multiple inheritance by defining method signatures without implementations.
2. Objectives:
Multithreaded Applications
Thread Life Cycle
Thread Scheduling & Synchronization
Creating and Using Delegates
Events as special Delegates
The Standard Event Handler
Inheritance
3. Multithreaded Programming
The benefits of multithreaded programming
can be broken down into four major
categories:
Responsiveness
Resource sharing
Economy
Utilization
4. Multithreaded Programming: C# Example
using System;
using System.Threading;
public class ThreadedCounters {
public static void Main(){
Thread thread1 = new Thread(new ThreadStart(Counter1));
thread1.Start();
Thread thread2 = new Thread(new ThreadStart(Counter2));
thread2.Start();
}
public static void Counter1() {
for (int i = 0; i<10; i++) {
Console.WriteLine("Counter 1: "+i);
Thread.Sleep(35);
}
}
public static void Counter2() {
for (int i = 0; i<10; i++) {
Console.WriteLine("Counter 2: "+i);
Thread.Sleep(20);
}
}
}
6. A common problem that needs to be handled
when writing multithreaded program is thread
synchronization
This is necessary where more than one thread
needs to modify a certain object at a time
Let us consider the following unsafe banking
example demonstrating the need for
synchronization
Thread Scheduling & Synchronization:
7. Multithreaded Programming: C# Example
using System;
using System.Threading;
public class BankAccount {
int balance = 0;
public BankAccount(int initial) {
balance = initial;
}
public void Deposit(int amount) {
balance+=amount;
}
public void Withdraw(int amount) {
balance-=amount;
}
public int GetBalance() {
return balance;
}
}
public class UnsafeBanking {
static Random randomizer = new Random();
static BankAccount account = new BankAccount(100);
public static void Main() {
Thread[] banker = new Thread[10];
for (int i=0; i<10; i++) {
banker[i] = new Thread(new
ThreadStart(DepositWithdraw));
banker[i].Start();
}
}
public static void DepositWithdraw() {
int amount = randomizer.Next(100);
account.Deposit(amount);
Thread.Sleep(100);
account.Withdraw(amount);
Console.WriteLine(account.GetBalance());
}
}
9. Thread Scheduling & Synchronization:
From the previous code, since the amount being
deposited is the same as the amount withdrawn,
one would expect the balance to remain unchanged
But, this is not what happens as the following
output shows:
10. Solving the
Synchronization
in C#:
C# uses the Monitor Class, which provides two
static methods, Enter and Exit
The Enter method is used to obtain a lock on an
object that the monitor guards and is called
before accessing the object
If the lock is currently owned by another thread,
the thread that calls Enter blocks
That is, the thread is taken off the processor and
placed in a very efficient wait state until the lock
becomes free
Exit frees the lock after the access is complete
so that other threads can access the resource
11. Solving the Synchronization in C#:
public static void DepositWithdraw() {
int amount = randomizer.Next(100);
Monitor.Enter(account);
try {
account.Deposit(amount);
Thread.Sleep(100);
account.Withdraw(amount);
Console.WriteLine(account.GetBalance());
}
finally {
Monitor.Exit(account); } }
public static void DepositWithdraw() {
int amount = randomizer.Next(100);
lock(account) {
account.Deposit(amount);
Thread.Sleep(100);
account.Withdraw(amount);
Console.WriteLine(account.GetBalance());
}
}
12. Delegates
A Delegate is a class whose declaration syntax
is different from that of a normal class
It is used to hold references to methods, so
that when it is invoked, it automatically invokes
all methods associated with it
Thus, a delegate gives an indirect access to a
method or methods, hence the name delegate
13. Delegates
using System;
public class DelegateExample {
public delegate void PrintingDelegate(String s);
public static void Writer1(String s) {
Console.WriteLine("From Writer1: "+s); }
public static void Writer2(String s) {
Console.WriteLine("From Writer2: "+s); }
public static void Main() {
PrintingDelegate d = new PrintingDelegate(Writer1);
d("Hello There");
//can point to more than one method
d += new PrintingDelegate(Writer2);
Console.WriteLine();
d("Hello There");
//can also point to instance method
Console.WriteLine();
MessageWriter mw = new MessageWriter();
d+= new PrintingDelegate(mw.WriteMessage);
d("Hello There");
//You can also remove a method
Console.WriteLine();
d-= new PrintingDelegate(Writer1);
d("Hello There"); } }
public class MessageWriter {
public void WriteMessage(String s) {
Console.WriteLine("From MessageWriter: "+s); }}
14. Delegate Declaration
Notice that although delegate is a class, its
declaration syntax is very similar to that of a
method
It is designed this way because a delegate can only
hold references to specific types of methods –
those methods whose signature matched that of
the delegate.
Thus, in our example, the PrintingDelegate can only
hold references to methods of the form:
[static] void MethodName(String s)
As the above example shows, such methods can be
static or instance
15. Instantiating a
Delegate
Before you create an instance of a delegate, you
must have a method that you wish to associate
that instance with. As we can see from the
example, the syntax is:
DelegateType delegateVar = new
DelegateType(methodName);
Notice that the method name must NOT be
followed with parameters
Actually a method name without parameter means
a reference to the method. So the above
statement assigns the method reference to the
delegateVar delegate instance
16. Inheritance
Generally speaking, objects are defined in terms
of classes. You know a lot about an object by
knowing its class
Inheritance offers the following benefits:
Subclasses provide specialized behaviors from the
basis of common elements provided by the superclass
Through the use of inheritance, programmers can reuse
the code in the superclass many times
Programmers can implement superclasses called
abstract classes that define common behaviors
• The abstract superclass defines and may partially
implement the behavior, but much of the class is
undefined and unimplemented. Other programmers fill in
the details with specialized subclasses.
17. Inheritance
The following is specific to C#
Again there is no “extend” keyword. Instead, the same
colon used for “implements” is used
If a class extends a class and implements one or more
interfaces, there should be only one colon
The super class and the interfaces are then listed
separated by commas
Notice that if there is a super class being extended,
then it must appear first in the list
18. Inheritance
The keyword, base, is used instead of the Java’s super, to
refer to a superclass member.
Also it is used to call the constructor of the base class from
within a subclass. However, like this keyword, such a call
should be in the heading of the calling constructor.
Example:
class B:A {
public B : base(. . .) {
. . .
} }
19. Inheritance
Overriding & Hiding
In C#, overriding is not allowed by default.
The base class must indicate that it is willing to allow its
method to be overridden by declaring the method as
virtual, abstract or override.
The subclass must also indicate that it is overriding the
method by using the override keyword.
The effect of overriding is the same as in Java –
Polymorphism. At run-time, a method call will be bound to
the method of the actual object.
A subclass may also decide to hide an inherited method
instead of overriding it by using the new keyword as the
following example shows.
20. Overriding,
Hiding Example
in C#
using System;
class A {
public virtual void method() {
Console.WriteLine(" In A");
}
}
class B : A {
public override void method() {
Console.WriteLine("In B");
}
}
class C : B {
public new void method() {
Console.WriteLine("In C");
}
}
class Test {
public static void Main() {
C c = new C();
c.method(); // calls C's method
B b = c;
b.method(); //calls B's method
A a = c;
a.method(); //calls B's method
}
}
21. Interfaces
In general, an interface is a device or a system that
unrelated entities use to interact
Interfaces are used to minimize the effect of lack of
multiple inheritance
Interfaces contain only method specification without
implementation
Unlike Java, interfaces cannot have even constant
fields
A class can implement multiple interfaces. However,
there is no “implements” keyword. Instead, a colon is
used for implements
22. Interfaces
You use an interface to define a protocol of behavior
that can be implemented by any class anywhere in the
class hierarchy. Interfaces are useful for the
following:
Capturing similarities among unrelated classes without
artificially forcing a class relationship
Declaring methods that one or more classes are expected to
implement
Revealing an object's programming interface without
revealing its class
Modeling multiple inheritance, a feature that some object-
oriented languages support that allows a class to have more
than one superclass