1 / 49

C# Programming

Lecture 6 “Assemblies in .NET & Threads”. C# Programming. Lecture 6. Assemblies in .NET Assemblies Threads in .NET How to use Concurrency. Assembly . Windows vs .NET What is the difference between a standard executable unit under Windows and one in a .NET environment Windows

dawson
Download Presentation

C# Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PGL01/ISCSH/2010 Lecture 6 “Assemblies in .NET & Threads” C# Programming

  2. PGL01/ISCSH/2010 Lecture 6 • Assemblies in .NET • Assemblies • Threads in .NET • How to use • Concurrency

  3. PGL01/ISCSH/2010 Assembly • Windows vs .NET • What is the difference between a standard executable unit under Windows and one in a .NET environment • Windows • only one executable unit: *.exe (old: *.com) • .NET • container type unit called assembly (contains: *.exe and/or *.dll) • What is an assembly • primary building block of a .NET Framework application!

  4. PGL01/ISCSH/2010 Assemblies • Assemblies are selfdescribing installation units • can contain one ore more files • resource files • metadata • dll’s • exe’s • can be private or shared • private • assembly can only be used in your own application • installed at the same time that your application is • location: same root-map as application source • shared • several applications can use the assembly and have a dependancy on it • contains a special version number and a unique name • location: Global Assembly Cache(GAC)

  5. PGL01/ISCSH/2010 Global Assembly Cache (GAC) • Cache for globally available Assemblies • also contains native code generated apps • created with native image generator (Ngen.exe) • Location: • C:\WINDOWS\assembly

  6. PGL01/ISCSH/2010 Assemblies • Assemblies are self-describing • no searching in the registry needed • metadata included in the assembly • types exported from the assembly • Assemblies have a manifest • version dependencies are recorded here • Assemblies can be loaded: side-by-side • different versions of the same dll can be used simultaniously • Application isolation ensured in assemblies • using: application domains • number of apps can run inside same process • errors in one app do not affect other apps

  7. PGL01/ISCSH/2010 Viewing Assemblies • Use: ildasm.exe

  8. PGL01/ISCSH/2010 Creating an EXE (assembly)

  9. PGL01/ISCSH/2010 Creating a DLL (assembly)

  10. PGL01/ISCSH/2010 Creating a DLL (assembly) cont’d namespace ClassLibrary1 { public class Demo { public void AMethod() { Console.WriteLine("AMethod() called!"); } public void BMethod() { Console.WriteLine("BMethod() called!"); } } }

  11. PGL01/ISCSH/2010 Calling the DLL in a program • Add assembly to application: • functionality visible throughobject browser:

  12. PGL01/ISCSH/2010 Calling the DLL in a program cont’d using System; using System.Collections.Generic; using System.Text; using ClassLibrary1; namespace ConsoleApp { class Program { static void Main(string[] args) { Demo demo = new Demo(); demo.AMethod(); demo.BMethod(); } } }

  13. PGL01/ISCSH/2010 “Threads” C# Programming

  14. PGL01/ISCSH/2010 Lecture 6 • Threads • What are threads • How to use threads • Concurrency

  15. PGL01/ISCSH/2010 Threads • What is it? • a thread runs in a program • cannot run on it’s own • a thread has a beginning and an end • just like the program • a thread runs independent of the program • the program can control the thread (start, stop, suspend, etc.) • there can be more than one thread in a program • all run independent of each other • every program has a main-thread • it runs the program • Definition:  A thread is a single sequential flow of control within a program.

  16. PGL01/ISCSH/2010 Thread example suspend thread 1 thread 1 stops thread 2 stops start thread 1 resume thread 1 start thread 2 program starts program ends main thread thread 1 thread 1 thread 2

  17. PGL01/ISCSH/2010 How do threads work? • Multithreading is managed internally by a thread scheduler • CLR delegates this to the operating system • ensures all active threads are allocated appropriate execution time (time-slicing) • not all threads run at the same time • Threads that are waiting or blocked • do not consume CPU time.

  18. PGL01/ISCSH/2010 How do threads work? • Preempted Multithreading • execution is interrupted due to an external factor(time-slicing) • In most situations, a thread has no control over when and where it's preempted • Time-slicing (single-processor computer) • rapidly switching execution between each of the active threads. This results in "choppy" behavior • Time-slicing (multi-processor computer) • Thread execution distributed over available processors (“real concurrency”)

  19. PGL01/ISCSH/2010 Creating threads in C# • Decide on the method to be run by the thread (can be static or instance) • Method must have the signature: void SomeMethod(); • Instantiate a thread delegate System.Threading.ThreadStart • Create the thread, represented by System.Threading.Thread • Finally, you start the thread using the method. Thread.Start()

  20. PGL01/ISCSH/2010 Example class Program { public Program() { ThreadStart start = new ThreadStart(ListNumbers); Thread t = new Thread(start); t.Start(); for (int n = 0; n < 1000; n++) Console.Write (“."); } public void ListNumbers() { for (int n = 0; n < 1000; n++) Console.Write(“o"); } static void Main(string[] args) { new Program(); } }

  21. PGL01/ISCSH/2010 Thread Priorities • Mechanism to make some threads more important than other threads • therefore run them more often • works both ways • lowering & raising priorities • can have undesired effects • starvation • low-priority thread never runs because other threads have higher priority

  22. PGL01/ISCSH/2010 Example class Program { private Thread t1, t2, t3; public Program() { t1 = new Thread(new hreadStart(ListNumbers1)); t2 = new Thread(new hreadStart(ListNumbers2)); t3 = new Thread(new hreadStart(ListNumbers3)); t1.Priority = ThreadPriority.Highest; t2.Priority = ThreadPriority.Highest; t3.Priority = ThreadPriority.Lowest; t1.Start(); t2.Start(); t3.Start(); }

  23. PGL01/ISCSH/2010 Example public void ListNumbers1() { for (int n = 0; n < 1000; n++) Console.Write("."); } public void ListNumbers2() { for (int n = 0; n < 1000; n++) Console.Write("o"); } public void ListNumbers3() { for (int n = 0; n < 1000; n++) Console.Write("-"); } static void Main(string[] args) { new Program(); } }

  24. PGL01/ISCSH/2010 Example Thread priority not set . – o mixed up . Thread priority set o -

  25. PGL01/ISCSH/2010 passing parameters to threads • use: • ParameterizedThreadStart • public delegate void ParameterizedThreadStart (object obj); class ThreadTest {  static void Main() {    ParameterizedThreadStart s = new ParameterizedThreadStart(Go); Thread t = new Thread (s);    t.Start(true); Go(false);  }  static void Go (object upperCase) {    bool upper = (bool) upperCase;    Console.WriteLine (upper ? "HELLO!" : "hello!");  } }

  26. PGL01/ISCSH/2010 passing parameters to threads Implicitly use: ParameterizedThreadStart public delegate void ParameterizedThreadStart (object obj); class ThreadTest {  static void Main() {    Thread t = new Thread (Go);    t.Start (true); Go (false);  }  static void Go (object upperCase) {    bool upper = (bool) upperCase;    Console.WriteLine (upper ? "HELLO!" : "hello!");  } }

  27. PGL01/ISCSH/2010 passing parameters to threads • use: anonymous method static void Main() {  Thread t = new Thread (delegate() { WriteText ("Hello"); });  t.Start(); } static void WriteText (string text) { Console.WriteLine (text); }

  28. PGL01/ISCSH/2010 Naming threads class ThreadNaming {  static void Main() {    Thread.CurrentThread.Name = "main";    Thread worker = new Thread (Go);    worker.Name = "worker";    worker.Start();    Go();  }  static void Go() {    Console.WriteLine ("Hello from " + Thread.CurrentThread.Name);  } } • Naming threads • can be named via its Name property • name can be set at any time • but only once • subsequently change will throw an exception

  29. PGL01/ISCSH/2010 “Concurrency & Synchronisation” C# Programming

  30. PGL01/ISCSH/2010 Concurrency & Synchronization • Concurrency • computations that execute overlapped in time, • sharing of resources between those computations • Synchronization • multiple threads share variable(s) (Competition) • is necesssary when the order of execution of the threads is important (Cooperation)

  31. PGL01/ISCSH/2010 Synchronisation What happens when 2 threads share a common variable?

  32. PGL01/ISCSH/2010 Synchronisation • Solution • make sure that while one thread is in a read/increment/write operation, no other threads can try to do the same thing • We need a guard that enables exclusive acces to that code • Guard object is called: Monitor

  33. PGL01/ISCSH/2010 Monitor • Every object in .NET has a (theoretical) monitor associated with it. • A thread can enter (or acquire) a monitor only if no other thread has currently "got" it. • The monitor is only available to other threads once it has been exited. • If a thread tries to acquire a monitor which is owned by another thread, it will block until it is able to acquire it.

  34. PGL01/ISCSH/2010 Solution • Use the monitor to enforce exclusive access to certain lines of code: try { Monitor.Enter(this) //code to be protected } finally { Monitor.exit(this) }

  35. PGL01/ISCSH/2010 Simplification try { Monitor.Enter(this) //code to be protected } finally { Monitor.exit(this) } lock(this){ //code to be protected }

  36. PGL01/ISCSH/2010 Synchronisation

  37. PGL01/ISCSH/2010 Thread lifecycle • What are the states a thread can hold? • When a thread starts • When a thread sleeps • When a thread is scheduled out • When a thread stops • When a thread waits • ….

  38. PGL01/ISCSH/2010 Threadstates new Thread Not Started Start() Deprecated threadpool Blocked: resume Suspended WaitSleepJoin pulse/pulseAll/sleep exp. interrupt Ready Δt suspend wait/sleep/join Running Abort() completed/aborted Stopped Aborted

  39. PGL01/ISCSH/2010 Normal thread lifecycle new Thread Not Started Start() threadpool Ready Δt Running completed/aborted Stopped

  40. PGL01/ISCSH/2010 Problem with concurrency Deadlock: 2 threads competing for the same resource

  41. PGL01/ISCSH/2010 In code class Program { private Thread t0, t1; private Object resourceA, resourceB; public Program() { t0 = new Thread(new ThreadStart(ThreadFunc0)); t1 = new Thread(new ThreadStart(ThreadFunc1)); resourceA = new Object(); resourceB = new Object(); t0.Start(); t1.Start(); }

  42. PGL01/ISCSH/2010 In code public void ThreadFunc0() { Console.WriteLine("Thread:0 trying to lock resource:A..."); lock (resourceA) { Console.WriteLine("Thread:0 waiting for resource:B..."); lock (resourceB) { Monitor.Wait(resourceB); } Console.WriteLine("Thread:0 locked both: doing work..."); Thread.Sleep(100); } }

  43. PGL01/ISCSH/2010 In code public void ThreadFunc1() { Console.WriteLine("Thread:1 trying to lock resource:B..."); lock (resourceB) { Console.WriteLine("Thread:1 waiting for resource:A..."); lock (resourceA) { Monitor.Wait(resourceA); } Console.WriteLine("Thread:1 locked both: doing work..."); Thread.Sleep(100); } }

  44. PGL01/ISCSH/2010 Thread Safety • Operations that can be performed from multiple threads safely, even if the calls happen simultaneously on multiple threads is said to be “Thread Safe” • All collections except Hashtable are not “thread safe”

  45. PGL01/ISCSH/2010 Good Threading models • The lazy worker thread • The thread falls asleep immediately • Wakes up when there's something to do • Solves the problem, and goes back to sleep • The single-shot task thread • Gets job description from the constructor • Performs the task immediately in run() • Emits done() when done, then exits

  46. PGL01/ISCSH/2010 Windows Controls and multithreading C# Programming

  47. PGL01/ISCSH/2010 Unsafe situation: When a control is accessed in a thread other than the thread it was created on public partial class Form1 : Form { Thread t; private void button1_Click(object sender, EventArgs e) { t = new Thread(Run); t.Start(); } private void Run() { textBox1.Text = “Hello Thread"; } }

  48. PGL01/ISCSH/2010 Solution: public delegate void TextCallback(String s); private void button1_Click(object sender, EventArgs e) { t = new Thread(Run); t.Start(); } private void Run() { if (textBox1.InvokeRequired) textBox1.Invoke(new TextCallback(SetText), new Object[] {"Hello World" }); } private void SetText(String s) { textBox1.Text = s; } Test a control with the property: “InvokeRequired”

  49. PGL01/ISCSH/2010 Lecture 6 • Reading Assignment • Professional C# 2008, • Chapter 17 in: Professional C# • Except: Creating Assemblies • Except: Dynamic Loading and Creating Assemblies • Except: Application Domains • Last: Using the Shared Assembly • Skip the rest • Chapter 19 • Except: Thread Pools • Except: Interlocked • Last: Mutex • Skip the rest

More Related