Documente Academic
Documente Profesional
Documente Cultură
NET
Keeping apps responsive by Adrian Magdas
Agenda
why and when to use threads Asynchronous Programming Model (APM) vs Event-Based Asynchronous Pattern (EAP) ThreadPool class Timers TPL(Task Parallel Library .NET 4+) - quick coverage good/best practices
Agenda (cont.)
issues: deadlocks, race conditions, thread starvation, High CPU quick coverage of basic synchronization constructs Interlocked constructs queue based communication, optimization techniques recommended documentation
Basics
Thread: wrapper over Windows native thread foreground vs background threads Thread pool: - worker threads for compute bound operations: ThreadPool. QueueUserWorkItem - IO bound from APM(file access, network, hardware) BackgroundWorker - don't use it as a timer or restart it a lot
Timers
System.Windows.Forms.Timer(EAP) - runs on UI thread, no synchronization needed System.Timers.Timer(EAP and ComponentModel) - do not use, wrapper over Threading.Timer System.Threading.Timer - this should be the default choice when a timer is needed
Best practices
when using ThreadPool threads, don't block the thread, make all work atomic if possible always check for exceptions - in APM safely thrown on EndInvoke() - on manually created threads, if the exception is not caught inside the thread, an unhandled exception is thrown - KO design the application to minimize the number of locks required no locks inside for loops - KO
Best practices(cont.)
avoid too many context switches to UI thread, use a Timer to control the frequency and measure, 200-300ms should be fine avoid locking on the UI thread, modify the architecture if needed - see OrderBook V2 avoid locking on "this" or class name, narrow down the lock USE ThreadPool use SynchronizedQueue if you want to implement Thread Pool pattern: see OrderBook V2
References
CLR via C# - Jeffrey Richter PFX Team Microsoft http://blogs.msdn.com/b/pfxteam/ Joe Duffy http://www.bluebytesoftware.com/blog/Default.
aspx
Synchronized Queue
development\ultrader\nOdisys\SynchronizedQueue.cs