- APM - allowing some portions of code to run on separate threadds.
- Many classes support APM - supply BeginXXX and EndXXX. e.g. FileStreamBeginRead(), EndRead(). Allows asynch. execution of mthds.
- EndXXX(
) - calling this blocks until asynch work is complete. - Rendevous Models - informs when to call EndXXX(). 3 models - Wait-Until-Done, polling, callback.
- wait-until-done:
- 1) strm.BeginRead(buffer,0,buffer.Length,null,null); - null for last 2 args as not Callback.
- polling:
- 1) while (!result.IsCompleted){//do work here Thread.Sleep(100);}
- callback model:
- 1) Create new AsyncCallback delegate (on another thread) when operation is complete - strmBeginRead(buffer,o,buffer.Length,new AsyncCallback(CompleteRead),strm);
- ThreadPool - built-in, and can be used in many situations where might expect to to create own threads.
- 1) WaitCallback workItem = new WaitCallback(WorkWithParameter);
- 2) ThreadPool.QueueUserWorkItem()
- ThreadPool - faster - threads reused + saves expensive setup costs. As threads become available, the thread pool posts new work to the thread.
- change threa pool thread limits - 1) thread starvation, 2) startup thread speed.
Tuesday, 13 November 2007
Chapter 7, lesson 3: Asynchronous Programming Model (APM).
Chapter 7, lesson 2: Sharing Data.
- We can share data bet. multiple threads.
- multithreading - multiple thredas might be interrogating our objs simult.
- Interlocked.Increment - adds 1 to value as atomic operation.
- Interlocked Class - only works with small number of .NET types.
Syncronization Locks
- Synch locks - to allow one to synch. access to objects in .NET. Can synch access to your own classes + treat larger sections of code as atomic.
- deadlocks - be careful!!
Other Synch. Mthds.
- ReaderWriterLock class - lock access to readers and writers separately - allow mult. concurrent readers but only a sinlge writer.
- To acquire a reader lock:
- 1) Instance of ReaderWriterLock class - to be shared across any threads.
- 2) try/catch block - catch ApplicationException - where acquisition of reader lock fails.
- 3) acquire lock - ReaderWriterLock.AcquireReaderLock.
- 4) try/finally - to hold any read code. thread-safe read in try, release lock in finally.
- To acquire a wrtier lock - analogous.
- Windows kernel objs - Mutex, Semaphore, Event.
- Much slower than using Monitor.
- When to use?:
- 1) Mutex - allows synch. across AppDomain and process boudaries.
- 2) Semaphore - throttles access to a resource to a set no. of threads.
- 3) Event - provides a way to notify mult. threads - across AppDomain and process boundaries - that some event has occurred.
- Mutex
- 1) create instance of Mutex to be shared across any threads - Mutex m = new Mutex();
- 2) WiatOne - to wait until lock is available.
- 3) try/finally - try - do thread-safe work - finally - release lock.
Monday, 12 November 2007
Chapter 7, lesson 1: Threading.
Threading - performing multiple operations concurrently.
- Thread class - to create + start threads.
- ThreadState enumeration - e.g. ThreadState.Aborted.
- create a thread - 1) create mthd which will run on thread - ret. void, no param.
- 2) wrap mthd in ThreadStart delegate - ThreadStart operation = new ThreadStart(dispatcher);
- 3) create thread - Thread theThread = new Thread(operation);
- 4) start thread - theThread.Start();
- Thread.Sleep - allows other threads to perform work.
- Join() - makes app wait until a thread has completed.
- ParamterizedThreadStart delegate - mthd signature has single param of type Object. Ret. void. In dispatcher(), test that obj passed in is of expected type.
Stopping Threads
- Thread.Abort() - where dispatcher() doesn't catch ThreadAbortExeception(), thread stops at line currently executing when main thread calls Abort. Inconsistent termination point, irrespective of whether exception is caught.
- BeginCriticalRegion, EndCriticalRegion - A critical region is a section of code that must be executed as if it were a single stmt. Any attempt to abort while within a critical region will have to wait until completion.
Execution Cnotext
- Each thread has data associated with it - Security info (IPrincipal + thread ID), localization settings (e.g. culture thread is running in), txn info.
- This contexct info is usually propogated to new threads.
- default - execution context flows to helper threads.
- ExecutionContext.SuppressFlow - can stop this - increases perf.
Chapter 6, Lesson 3 - Formatting Text & adding to images.
Adding Text to Graphics
- Cretae Graphics obj.
- Create Font obj. - e.g. Font f = new Font("Arial",12,FontStyle.Bold);
- Create Brush obj. (to describe how text will be filled) OR provide System.Drawing.Brushes property - Graphics g = this.CreateGraphics(); Font f = new Font("Arial",40,FontStyle.Bold); g.DrawString("Hello",f,Brushes.Blue,10,10);
Wednesday, 7 November 2007
Chapter 6, Lesson 2 - Working with Images.
To display, create & modify images.
- System.Drawing.Image
- abstract class.
- to create, load, modify, save .BMP, .JPG, .TIF files.
- Bitmap Class - inherits from Image - for still images.
- MetaFile Class - inherits from Image - for animated images.
- Bitmap.GetPixel() - Returns a Color obj describing a particular pixel in the image.
- Bitmap.SetPixel() - ...to a specific colour.
- display an image in a form #1 - 1) load it - Image.FromFile(), 2) create a PictureBox control, 3) set image obj to background - pictureBox1.BackgroundImage = i;
- display an image in a form #2 - 1) new Bitmap(); 2)
.CreateGraphics(); 3) DrawImage(). - create a new, blank picture - create instance of Bitmap class that does not require an existing image.
- Edit new image - Bitmap.SetPixel or Graphics.FromImage().
- icons -
Chapter 6, Lesson 1 - Drawing Graphics.
UI - brushes, pens, colours, fonts
lines, circles, shapes.
System.Drawing Namespace
lines, circles, shapes.
System.Drawing Namespace
- circles, lines, create charts, edit/resize pics.
- Graphics class - most used - mths for drawing to display device.
- Pen class - draw lines & curves.
- Brush class (abstract) - fills interiors of shapes.
- PictureBox class - use in Windows Forms apps to display image as part of UI.
- System.Drawing structures - Color, Point, Rectangle, Size.
- Specify location of control - set control's Location property using Point structure - button1.Location = new Point(10,10);
- Specify size of control - set control's Size property using Size structure - button1.Size = new Size(30,30);
- Specify colour - Color structure -> ForeColor/BackColor.
- Specify custom colour - Color.FromArgB() -> ForeColor/BackColor.
- To draw on form/control - 1) create Graphics obj - System.Windows.Forms.Control.CreateGraphics(), 2) create Pen obj, 3) call member of Graphics class to draw on control. e.g. g.DrawLine(p,1,1,100,100);
- endcaps - ends of a line.
- Pens - can customiize Color + Size of Pen, and also Pattern (p.DashStyle = DashStyle.Dot) and Endcaps (StartCap/EndCap).
- Filling shapes - most Graphics Draw mthds have corresponding Fill mthds, that require Brush instead of Pen.
Tuesday, 6 November 2007
Chapter 5, lesson 3: Custom Serialization.
Custom Serialization - process of controlling the serialization/deserialization of a type.
use: serialization compatibility - ability to serialize/deserialize between versions of a type without breaking core functionality of type. (e.g. vers. n+1 needs to be able to deserialize objs of vers n).
Custom Serialization
use: serialization compatibility - ability to serialize/deserialize between versions of a type without breaking core functionality of type. (e.g. vers. n+1 needs to be able to deserialize objs of vers n).
Custom Serialization
- override default serialization built-in to .NF - impl. ISerializable interface + apply Serializable attr to class.
- when? 1) when value of member variable is invalid after deserialization, 2) when class to serialize is marked with Serializable attr. + has declarative or imperative security.
- how impl. ISerializable interface? impl. GetObjectData() - for during serialization - special constructor - during deserialization. SerializationInfo obj - AddValue() - add variables to be serialized as name/value pairs.
- respond to serialization events - to alter obj <> (de)serialization. Mthd must 1) accept StreamingContext object, 2) ret. void, 3) be decorated with attr. that you want to intercept.
- StreamingContext structure - provides info re. the destination of a serialized object, toclasses that impl. ISerializable interface.
Subscribe to:
Posts (Atom)