0% found this document useful (0 votes)
14 views19 pages

Understanding C# Delegates and Reflection

The document provides an overview of C# delegates, reflection, and multithreading, explaining their definitions, uses, and examples. Delegates are described as type-safe method references, while reflection allows access to type metadata at runtime. Multithreading is discussed in terms of thread lifecycle, properties, and methods, with examples illustrating the creation and execution of threads.

Uploaded by

dannluci676
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views19 pages

Understanding C# Delegates and Reflection

The document provides an overview of C# delegates, reflection, and multithreading, explaining their definitions, uses, and examples. Delegates are described as type-safe method references, while reflection allows access to type metadata at runtime. Multithreading is discussed in terms of thread lifecycle, properties, and methods, with examples illustrating the creation and execution of threads.

Uploaded by

dannluci676
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C# Delegates

In C#, delegate is a reference to the method. It works like function pointer in C and C++.
But it is objected-oriented, secured and type-safe than function pointer.

For static method, delegate encapsulates method only. But for instance method, it
encapsulates method and instance both.

The best use of delegate is to use as event.

Internally a delegate declaration defines a class which is the derived class


of [Link].

C# Delegate Example
Let's see a simple example of delegate in C# which calls add() and mul() methods.

1. using System;
2. delegate int Calculator(int n);//declaring delegate
3.
4. public class DelegateExample
5. {
6. static int number = 100;
7. public static int add(int n)
8. {
9. number = number + n;
10. return number;
11. }
12. public static int mul(int n)
13. {
14. number = number * n;
15. return number;
16. }
17. public static int getNumber()
18. {
19. return number;
20. }
21. public static void Main(string[] args)
22. {
23. Calculator c1 = new Calculator(add);//instantiating delegate
24. Calculator c2 = new Calculator(mul);
25. c1(20);//calling method using delegate
26. [Link]("After c1 delegate, Number is: " + getNumber());
27. c2(3);
28. [Link]("After c2 delegate, Number is: " + getNumber());
29.
30. }
31. }

Output:

After c1 delegate, Number is: 120


After c2 delegate, Number is: 360

C# Reflection
In C#, reflection is a process to get metadata of a type at runtime. The [Link]
namespace contains required classes for reflection such as:

o Type

o MemberInfo

o ConstructorInfo

o MethodInfo

o FieldInfo

o PropertyInfo

o TypeInfo

o EventInfo

o Module

o Assembly

o AssemblyName

o Pointer etc.

The [Link] namespace contains classes to emit metadata.

C# Type class
C# Type class represents type declarations for class types, interface types, enumeration
types, array types, value types etc. It is found in System namespace. It inherits
[Link] class.

C# Type Properties
A list of important properties of Type class are given below:
Property Description
Assembly Gets the Assembly for this type.

AssemblyQualifiedName Gets the Assembly qualified name for this type.

Attributes Gets the Attributes associated with the type.

BaseType Gets the base or parent type.

FullName Gets the fully qualified name of the type.

IsAbstract is used to check if the type is Abstract.

IsArray is used to check if the type is Array.

IsClass is used to check if the type is Class.

IsEnum is used to check if the type is Enum.

IsInterface is used to check if the type is Interface.

IsNested is used to check if the type is Nested.

IsPrimitive is used to check if the type is Primitive.

IsPointer is used to check if the type is Pointer.

IsNotPublic is used to check if the type is not Public.

IsPublic is used to check if the type is Public.

IsSealed is used to check if the type is Sealed.

IsSerializable is used to check if the type is Serializable.

MemberType is used to check if the type is Member type of Nested

Module Gets the module of the type.

Name Gets the name of the type.

Namespace Gets the namespace of the type.

C# Type Methods
A list of important methods of Type class are given below:

Method Description
GetConstructors() Returns all the public constructors for the Type.

GetConstructors(BindingFlags) Returns all the constructors for the Type with specified
GetFields() Returns all the public fields for the Type.

GetFields(BindingFlags) Returns all the public constructors for the Type with sp

GetMembers() Returns all the public members for the Type.

GetMembers(BindingFlags) Returns all the members for the Type with specified Bi

GetMethods() Returns all the public methods for the Type.

GetMethods(BindingFlags) Returns all the methods for the Type with specified Bin

GetProperties() Returns all the public properties for the Type.

GetProperties(BindingFlags) Returns all the properties for the Type with specified B

GetType() Gets the current Type.

GetType(String) Gets the Type for the given name.

C# Reflection Example: Get Type


1. using System;
2. public class ReflectionExample
3. {
4. public static void Main()
5. {
6. int a = 10;
7. Type type = [Link]();
8. [Link](type);
9. }
10. }

Output:

System.Int32

C# Reflection Example: Get Assembly


1. using System;
2. using [Link];
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof([Link]);
8. [Link]([Link]);
9. }
10. }

Output:

mscorlib, Version=[Link], Culture=neutral, PublicKeyToken=b77a5c561934e089

C# Reflection Example: Print Type Information


1. using System;
2. using [Link];
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof([Link]);
8. [Link]([Link]);
9. [Link]([Link]);
10. [Link]([Link]);
11. [Link]([Link]);
12. [Link]([Link]);
13. }
14. }

Output:

[Link]
[Link]
true
false
false

C# Reflection Example: Print Constructors


1. using System;
2. using [Link];
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof([Link]);
8.
9. [Link]("Constructors of {0} type...", t);
10. ConstructorInfo[] ci = [Link]([Link] | [Link])
;
11. foreach (ConstructorInfo c in ci)
12. {
13. [Link](c);
14. }
15. }
16. }

Output:

Constructors of [Link] type...


Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, [Link])
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char[])
Void .ctor(Char, Int32)

C# Reflection Example: Print Methods


1. using System;
2. using [Link];
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof([Link]);
8.
9. [Link]("Methods of {0} type...", t);
10. MethodInfo[] ci = [Link]([Link] | [Link]);
11. foreach (MethodInfo m in ci)
12. {
13. [Link](m);
14. }
15. }
16. }

Output:

Methods of [Link] type...


Boolean Equals([Link])
Boolean Equals([Link])
Boolean Equals([Link], [Link])
Char get_Chars(Int32)
Void copyTo(Int32, char[], Int32, Int32)
Char[] ToCharArray()
....

C# Reflection Example: Print Fields


1. using System;
2. using [Link];
3. public class ReflectionExample
4. {
5. public static void Main()
6. {
7. Type t = typeof([Link]);
8.
9. [Link]("Fields of {0} type...", t);
10. FieldInfo[] ci = [Link]([Link] | [Link] | BindingFlags.N
onPublic);
11. foreach (FieldInfo f in ci)
12. {
13. [Link](f);
14. }
15. }
16. }

Output:

Fields of [Link] type...


[Link] Empty
Int32 TrimHead
Int32 TrimTail
Int32 TrimBoth
Int32 charPtrAlignConst
Int32 alignConst

C# Multithreading
Multithreading in C# is a process in which multiple threads work simultaneously. It is a
process to achieve multitasking. It saves time because multiple tasks are being executed
at a time. To create multithreaded application in C#, we need to
use [Link] namespace.

Process and Thread


A process represents an application whereas a thread represents a module of the
application. Process is heavyweight component whereas thread is lightweight. A thread
can be termed as lightweight subprocess because it is executed inside a process.
Whenever you create a process, a separate memory area is occupied. But threads share
a common memory area.

C# Thread Life Cycle


In C#, each thread has a life cycle. The life cycle of a thread is started when instance of
[Link] class is created. When the task execution of the thread is
completed, its life cycle is ended.

There are following states in the life cycle of a Thread in C#.

o Unstarted

o Runnable (Ready to run)

o Running

o Not Runnable

o Dead (Terminated)

Unstarted State
When the instance of Thread class is created, it is in unstarted state by default.

Runnable State
When start() method on the thread is called, it is in runnable or ready to run state.

Running State
Only one thread within a process can be executed at a time. At the time of execution,
thread is in running state.

Not Runnable State


The thread is in not runnable state, if sleep() or wait() method is called on the thread, or
input/output operation is blocked.

Dead State
After completing the task, thread enters into dead or terminated state.

C# Thread class
C# Thread class provides properties and methods to create and control threads. It is
found in [Link] namespace.
C# Thread Properties
A list of important properties of Thread class are given below:

Property Description

CurrentThread returns the instance of currently running thread.

IsAlive checks whether the current thread is alive or not. It is used to find the exe

IsBackground is used to get or set value whether current thread is in background or not.

ManagedThreadId is used to get unique id for the current managed thread.

Name is used to get or set the name of the current thread.

Priority is used to get or set the priority of the current thread.

ThreadState is used to return a value representing the thread state.

C# Thread Methods
A list of important methods of Thread class are given below:

Method Description

Abort() is used to terminate the thread. It raises ThreadAbortException.

Interrupt() is used to interrupt a thread which is in WaitSleepJoin state.

Join() is used to block all the calling threads until this thread terminates.

ResetAbort() is used to cancel the Abort request for the current thread.

Resume() is used to resume the suspended thread. It is obselete.

Sleep(Int32) is used to suspend the current thread for the specified milliseconds.

Start() changes the current state of the thread to Runnable.

Suspend() suspends the current thread if it is not suspended. It is obselete.


Yield() is used to yield the execution of current thread to another thread.

C# Main Thread Example


The first thread which is created inside a process is called Main thread. It starts first and
ends at last.

Let's see an example of Main thread in C#.

1. using System;
2. using [Link];
3. public class ThreadExample
4. {
5. public static void Main(string[] args)
6. {
7. Thread t = [Link];
8. [Link] = "MainThread";
9. [Link]([Link]);
10. }
11. }

Output:

MainThread

C# Threading Example: static method


We can call static and non-static methods on the execution of the thread. To call the
static and non-static methods, you need to pass method name in the constructor of
ThreadStart class. For static method, we don't need to create the instance of the class.
You can refer it by the name of class.

1. using System;
2. using [Link];
3. public class MyThread
4. {
5. public static void Thread1()
6. {
7. for (int i = 0; i < 10; i++)
8. {
9. [Link](i);
10. }
11. }
12. }
13. public class ThreadExample
14. {
15. public static void Main()
16. {
17. Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
18. Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));
19. [Link]();
20. [Link]();
21. }
22. }

Output:

The output of the above program can be anything because there is context switching
between the threads.

0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9

C# Threading Example: non-static method


For non-static method, you need to create instance of the class so that you can refer it in
the constructor of ThreadStart class.

1. using System;
2. using [Link];
3. public class MyThread
4. {
5. public void Thread1()
6. {
7. for (int i = 0; i < 10; i++)
8. {
9. [Link](i);
10. }
11. }
12. }
13. public class ThreadExample
14. {
15. public static void Main()
16. {
17. MyThread mt = new MyThread();
18. Thread t1 = new Thread(new ThreadStart(mt.Thread1));
19. Thread t2 = new Thread(new ThreadStart(mt.Thread1));
20. [Link]();
21. [Link]();
22. }
23. }

Output:

Like above program output, the output of this program can be anything because there is
context switching between the threads.

0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9

C# Threading Example: performing different


tasks on each thread
Let's see an example where we are executing different methods on each thread.

1. using System;
2. using [Link];
3.
4. public class MyThread
5. {
6. public static void Thread1()
7. {
8. [Link]("task one");
9. }
10. public static void Thread2()
11. {
12. [Link]("task two");
13. }
14. }
15. public class ThreadExample
16. {
17. public static void Main()
18. {
19. Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
20. Thread t2 = new Thread(new ThreadStart(MyThread.Thread2));
21. [Link]();
22. [Link]();
23. }
24. }

Output:

task one
task two

C# Threading Example: Sleep() method


The Sleep() method suspends the current thread for the specified milliseconds. So, other
threads get the chance to start execution.

1. using System;
2. using [Link];
3. public class MyThread
4. {
5. public void Thread1()
6. {
7. for (int i = 0; i < 10; i++)
8. {
9. [Link](i);
10. [Link](200);
11. }
12. }
13. }
14. public class ThreadExample
15. {
16. public static void Main()
17. {
18. MyThread mt = new MyThread();
19. Thread t1 = new Thread(new ThreadStart(mt.Thread1));
20. Thread t2 = new Thread(new ThreadStart(mt.Thread1));
21. [Link]();
22. [Link]();
23. }
24. }

Output:

0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9

C# Threading Example: Abort() method


The Abort() method is used to terminate the thread. It raises ThreadAbortException if
Abort operation is not done.

1. using System;
2. using [Link];
3. public class MyThread
4. {
5. public void Thread1()
6. {
7. for (int i = 0; i < 10; i++)
8. {
9. [Link](i);
10. [Link](200);
11. }
12. }
13. }
14. public class ThreadExample
15. {
16. public static void Main()
17. {
18. [Link]("Start of Main");
19. MyThread mt = new MyThread();
20. Thread t1 = new Thread(new ThreadStart(mt.Thread1));
21. Thread t2 = new Thread(new ThreadStart(mt.Thread1));
22.
23. [Link]();
24. [Link]();
25. try
26. {
27. [Link]();
28. [Link]();
29. }
30. catch (ThreadAbortException tae)
31. {
32. [Link]([Link]());
33. }
34. [Link]("End of Main");
35. }
36. }

Output:

Output is unpredictable because thread may be in running state.

Start of Main
0
End of Main

C# Threading Example: Join() method


It causes all the calling threads to wait until the current thread (joined thread) is
terminated or completes its task.
1. using System;
2. using [Link];
3. public class MyThread
4. {
5. public void Thread1()
6. {
7. for (int i = 0; i < 5; i++)
8. {
9. [Link](i);
10. [Link](200);
11. }
12. }
13. }
14. public class ThreadExample
15. {
16. public static void Main()
17. {
18. MyThread mt = new MyThread();
19. Thread t1 = new Thread(new ThreadStart(mt.Thread1));
20. Thread t2 = new Thread(new ThreadStart(mt.Thread1));
21. Thread t3 = new Thread(new ThreadStart(mt.Thread1));
22. [Link]();
23. [Link]();
24. [Link]();
25. [Link]();
26. }
27. }

Output:

0
1
2
3
4
0
0
1
1
2
2
3
3
4
4
C# Threading Example: Naming Thread
Let's see an example where we are setting and getting names of the threads.

1. using System;
2. using [Link];
3.
4. public class MyThread
5. {
6. public void Thread1()
7. {
8. Thread t = [Link];
9. [Link]([Link]+" is running");
10. }
11. }
12. public class ThreadExample
13. {
14. public static void Main()
15. {
16. MyThread mt = new MyThread();
17. Thread t1 = new Thread(new ThreadStart(mt.Thread1));
18. Thread t2 = new Thread(new ThreadStart(mt.Thread1));
19. Thread t3 = new Thread(new ThreadStart(mt.Thread1));
20. [Link] = "Player1";
21. [Link] = "Player2";
22. [Link] = "Player3";
23. [Link]();
24. [Link]();
25. [Link]();
26. }
27. }

Output:

Player1 is running
Player2 is running
Player3 is running

C# Threading Example: ThreadPriority


Let's see an example where we are changing the priority of the thread. The high priority
thread can be executed first. But it is not guaranteed because thread is highly system
dependent. It increases the chance of the high priority thread to execute before low
priority thread.
1. using System;
2. using [Link];
3. public class MyThread
4. {
5. public void Thread1()
6. {
7. Thread t = [Link];
8. [Link]([Link]+" is running");
9. }
10. }
11. public class ThreadExample
12. {
13. public static void Main()
14. {
15. MyThread mt = new MyThread();
16. Thread t1 = new Thread(new ThreadStart(mt.Thread1));
17. Thread t2 = new Thread(new ThreadStart(mt.Thread1));
18. Thread t3 = new Thread(new ThreadStart(mt.Thread1));
19. [Link] = "Player1";
20. [Link] = "Player2";
21. [Link] = "Player3";
22. [Link] = [Link];
23. [Link] = [Link];
24. [Link] = [Link];
25.
26. [Link]();
27. [Link]();
28. [Link]();
29. }
30. }

Output:

The output is unpredictable because threads are highly system dependent. It may follow
any algorithm preemptive or non-preemptive.

Player1 is running
Player3 is running
Player2 is running

You might also like