DAD Lab. 2 Additional C# Topics

Similar documents
Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd)

Systems Programming & Scripting

Lecture 21: Concurrency in Other Environments (Part 2)

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Exercise Session Week 8

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Exercise Session Week 8

Java Threads. COMP 585 Noteset #2 1

Threads are lightweight processes responsible for multitasking within a single application.

Contents. 6-1 Copyright (c) N. Afshartous

Java Threads. Introduction to Java Threads

Threads Chate Patanothai

The list abstract data type defined a number of operations that all list-like objects ought to implement:

CS11 Java. Fall Lecture 7

TEMPLATES AND EXCEPTION HANDLING

Introduction to Programming Using Java (98-388)

NOIDATUT E Leaning Platform

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Threads and Java Memory Model

7. MULTITHREDED PROGRAMMING

Lecture 8: Threads. Lisa (Ling) Liu

Ch 9: Control flow. Sequencers. Jumps. Jumps

Chapter 13 Working with Threads

CMSC 330: Organization of Programming Languages

G52CPP C++ Programming Lecture 16

Debugging and Handling Exceptions

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Performance Throughput Utilization of system resources

Threads & Networking

Object Oriented Programming Exception Handling

Fall 2017 CISC124 10/1/2017

Pace University. Fundamental Concepts of CS121 1

Chapter 1 Getting Started

Selected Java Topics

Concurrent Programming using Threads

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Multiple processes can run in parallel on a single computer and multiple threads can run in parallel in a single process.

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Programming II (CS300)

CS 556 Distributed Systems

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment.

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Lecture 5: Synchronization w/locks

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567)

CSC 1052 Algorithms & Data Structures II: Lists

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

COMP1008 Exceptions. Runtime Error

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

1B1b Classes in Java Part I

C# Threading. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Error Handling. Exceptions

Game Engineering: 2D

Multithreading Pearson Education, Inc. All rights reserved.

Advanced Concepts of Programming

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CPSC 427: Object-Oriented Programming

COE318 Lecture Notes Week 10 (Nov 7, 2011)

IS 0020 Program Design and Software Tools

Java Threads and intrinsic locks

Unit III Rupali Sherekar 2017

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

CS 209 Programming in Java #10 Exception Handling

CS 160: Interactive Programming

CS 231 Data Structures and Algorithms, Fall 2016

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Multi-threaded programming in Java

Polyphonic C# is an extension to the C# language Extension is aimed at providing in-language concurrency support

C++ Programming Fundamentals

Object-Oriented Programming

Concurrency, Thread. Dongkun Shin, SKKU

Synchronized Methods of Old Versions of Java

CS 351 Design of Large Programs Threads and Concurrency

Unit 5 - Exception Handling & Multithreaded

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Department of Computer Science. COS 122 Operating Systems. Practical 3. Due: 22:00 PM

Exception Examples. All examples written by Edith Hemaspaandra and modified by Jessica Bayliss

Operators. The Arrow Operator. The sizeof Operator

Java SE7 Fundamentals

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5

Intro to Threads. Two approaches to concurrency. Threaded multifinger: - Asynchronous I/O (lab) - Threads (today s lecture)

CMSC 132: Object-Oriented Programming II

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Transcription:

DAD 2017-2018 Lab. 2 Additional C# Topics

Summary 1. Properties 2. Exceptions 3. Delegates and events 4. Generics 5. Threads and synchronization

1. Properties Get/Set

Properties Simple way to control the access to the private attributes of classes, structs and interfaces public class X { private string name; private int age; public string Name { get { return name; set { name = value; (...) x.name = Smith ; Console.WriteLine( I m called {0", x.name); Formalizes the concept of Get/Set methods Makes code more readable

2. Exceptions Syntax Throwing Intercepting

Exceptions Should correspond to exceptional situations. Thrown by the system or using the throw command. Used by putting code inside a try-catch block: try { //code that generates the exception catch (<ExceptionType> e) { // handling of exception e finally { // is always executed // usually the release of allocated resources New exceptions can be created by deriving System.ApplicationException

Exception Throwing class MyException: ApplicationException { // arbitrary methods and attributes... if (<error condition>) { throw new MyException();

Exception Interception Go up the stack searching for a try block, Look for a matching catch block. If there is none, run the finally block And continue up the stack, executing the finally blocks until the exception is caught or the program is terminated.

Sample System Exceptions System.ArithmeticException System.ArrayTypeMismatchException System.DivideByZeroException System.IndexOutOfRangeException. System.InvalidCastException System.MulticastNotSupportedException System.NullReferenceException System.OutOfMemoryException System.OverflowException System.StackOverflowException System.TypeInitializationException

Exception Tips Dont throw exceptions for normal program control flow. Don t throw exceptions you re not going to handle. When you catch an exception but you need to throw it again, use the isolated throw clause. It avoids rewriting the exception stacktrace. try { //code that may generate the exception catch (<ExceptionType> e) { // handling of exception e throw; // instead of throw e;

3. Delegates and Events

Delegates Similar to function pointers: bool (*myfunction) (int) /* in C */ Pointers to object or class methods: delegate bool MyDelegate(int x); MyDelegate md = new MyDelegate(a_method); Delegates keep a list of methods. Can be manipulated with arithmetic operations: Combine (+), Remove (-) An empty delegate is equal to null.

Delegates (cont.) delegate void MyDelegate(string s); class MyClass { public static void Hello(string s) { Console.WriteLine(" Hello, {0!", s); public static void Goodbye(string s) { Console.WriteLine(" Goodbye, {0!", s); public static void Main() { MyDelegate a, b, c; a = new MyDelegate(Hello); b = new MyDelegate(Goodbye); c = a + b; a("a"); b("b"); c( C ); Hello, A! GoodBye, B! Hello, C! GoodBye, C!

Events Publish - Subscribe Publishing class: generates an event for the interested objects (the subscribers); Subscribing class: provides a method that is called when the event happens. The method called by an event must be a delegate: public delegate void MyDelegate( ); public event MyDelegate evt; Events have restricted permissions for subscribing classes: Subscribers can only use += and -=

Syntax Convention for Events Subscribing delegates return null: Return void. Take two arguments: 1 st : the object that generated the event 2 nd : an instance of a subclass of EventArgs public class MyEventArgs: EventArgs { private int a; public MyEventArgs(int a) { this. a = a; public int A { get {return a; public delegate void MySubs(object sender, MyEventArgs a); public event MySubs E;

Event Subscription public class MyClass { public void Callback(object sender, MyEventArgs e) { Console.Writeline( Fired {0, e.a);... MyClass c = new MyClass(); E += new MySubs(c.Callback);

Triggering an Event: Subscriber Notification public void TriggerEvent( ) { if (E!= null) E(this, new MeusEventArgs(0)); It s necessary to check whether there is at least one subscriber before triggering an event otherwise a exception is generated.

4. Generics (C# 2.0) Collections Classes Methods

Generics (C# 2.0) Allow the definition of strongly typed structures. Instead of: using System.Collections; ArrayList list = new ArrayList(); list.add(1); // should check if 1 is int int i = (int) list[0];,we can have: using System.Collections.Generics; List<int> list = new List<int>(); list.add(1); // no check needed int i = list[0]; // no cast needed

Generics (classes) Programmers can create generic classes: public class MyLista<T> { // T is any type T[] m_items; public MyLista ():this(100) { public MyLista (int size) { m_items = new T[m_Size]; public void Add(T item) { public T Remove(int index) { public T Get(int index) { And use it: MyLista<char> characters = new MyLista<char>(10); characters Add( c ); char character = characters.get(0); // no cast needed

Generics (methods) Programmers can also define methods using Generics: public class AClass { public T Add<T>(T item) { The type used is inferred during compile time. Use example: AClass c = new AClass(); c.add( c ); // Add(char) c.add(6); // Add(int)

5. Threads and Monitors

Threads When to use threads: Simultaneous tasks Sharing data Performance is more important than fault tolerance Construction: //ThreadStart is a public delegate void ThreadStart(); ThreadStart ts = new ThreadStart(y.xpto); Thread t = new Thread(ts); t.start(); // start execution t.join(); // wait for termination

Threads (cont.) Other methods: Abort, Sleep, Join using System; using System.Threading; public class Alpha { public void Beta() { while (true) { Console.WriteLine("A.B is running in its own thread."); ;

Threads (cont.) public class Simple { public static int Main() { Alpha oalpha = new Alpha(); Thread othread = new Thread(new ThreadStart(oAlpha.Beta)); othread.start(); // Spin for a while waiting for the started thread to become alive: while (!othread.isalive); // Put the Main thread to sleep for 1 ms to allow othread to work: Thread.Sleep(1); // Request that othread be stopped othread.abort();

Synchronization: Monitors Thread concurrency requires synchronization. lock primitive provides mutual exclusion. Two standard options: lock(this), mutual exclusion for all methods of one object. lock(typeof(this)), mutual exclusion for all methods of one class.

Synchronization (cont.) Monitors: Monitor.Enter(this); [equivalent to lock(this)] Gets an exclusive lock on the current object (this) Monitor.Wait(this); Releases the lock over the current object and blocks until it receives a Pulse. Monitor.Pulse(this); Wakes up one of the threads that called Wait. It will run again when it s alone in the current object. Monitor.PulseAll(this); Wakes up all the threads that called Wait on the current object. One will run again when it s alone in the current object. The others will block again. Monitor.Exit(this); Releases the exclusive lock on the current object. Reccomended reading: MSDN ( http://msdn2.microsoft.com/enau/library/system.threading.monitor.pulse.aspx )

Synchronization (WinForms) Many window systems (including WinForms) don t allow manipulation of UI controls by threads other than the one that created them (usually the UI thread) It s irrelevant in single-threaded applications. In multi-threaded applications, one should use: Control.InvokeRequired Returns a boolean indicating whether the current thread can invoke the control. Control.Invoke(Delegate) The thread where the control was created will call (synchronously) the delegate that is passed as an argument. Control.BeginInvoke(Delegate) The thread where the control was created will call (asynchronously) the delegate that is passed as an argument. Recommended reading: http://www.codeproject.com/csharp/begininvoke.asp