Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование в .NET

41 views

Published on

Раскрывается тема проектирования и реализации многопоточных и асинхронных приложений для платформы .NET. Обсуждаются вопросы создания потоков, их дальнейшего использования и синхронизации в контексте масштабируемости и быстродействия. Рассматриваются общие ошибки и заблуждения при проектировании многопоточности, а также способы повышения производительности.

Published in: Education
  • Be the first to comment

  • Be the first to like this

.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование в .NET

  1. 1. Multithreading & Async programming in .Net (Controversial topics and common mistakes) Vladimir Kramar
  2. 2. 1. What is a thread itself? 2. How to create a new thread? 3. Async - Why & Where? 4. Async & locking. 5. Exceptions in async methods. 6. Tricks & Hints. 7. Closing thoughts. Agenda
  3. 3. What is a thread itself?
  4. 4. How to create a new thread? • Thread • ThreadPool • System.Threading.Timer • APM - IAsyncResult, BeginInvoke(), EndInvoke() • EAP - BackgroundWorker • TAP - Task and Async / Await approach .Net 1.x .Net 2.0 .Net 4.x
  5. 5. System.Threading.Thread We should not use this class unless:  We need to set a stack size, apartment state or culture for a new thread.  We need immediately execute a new thread.  We need a task running in foreground mode.  We need a thread to have a particular priority.  We have a task that might run a long time.
  6. 6. Why not ThreadPool? ThreadPool can be used something like this: • Messy! Is not it? • What if we have to wait for many threads to complete? • How do we capture the return values from multiple threads? • How do we return the control back to GUI threads?
  7. 7. System.Threading.Timer No – Thread.Sleep() Yes – To using of Timer
  8. 8. Asynchronous Patterns • APM Asynchronous Programming Model (IAsyncResult) • EAP Event-based Asynchronous Pattern (BackgroundWorker) • TAP Task-based Asynchronous Pattern (Task & async / await)
  9. 9. IAsyncResult (with callback) IAsyncResult – with callback Async / Await – with void method
  10. 10. IAsyncResult – without callback Async / Await – with Task async method IAsyncResult (without callback)
  11. 11. Why Async / Await is better? • Implementing of one method instead of two. • More readable implementation. • Copying the thread context. • Ability to track async operations progress. • Ability to create cold async operations.
  12. 12. How to create a new thread? • TAP - Task and Async / Await approach • Thread • ThreadPool • System.Threading.Timer • APM - IAsyncResult, BeginInvoke(), EndInvoke() • EAP - BackgroundWorker In most cases: In some special cases: Do not use it:
  13. 13. Async – Why & Where?
  14. 14. Async – Why & Where? Difference between Multithreading and Asynchronous programming: Multithreading: Async (better approach):
  15. 15. Async – Why & Where? Difference between Multithreading and Asynchronous programming: Better just to execute it with a new thread: General methods can not be executed as asynchronous even if we use async / await:
  16. 16. Async – Why & Where?
  17. 17. Async – Why & Where? Why? – To increase scalability. Where? – Whenever it is possible for long-running operations.
  18. 18. Under a hood of Async / Await. Let’s look at this async method: Behind the scene it performs the following: • Copying all local variable values. • Copying ‘this’ object state. • Tracking some other state data like a current stack pointer, await number, etc. • Remembering Synchronization and other thread contexts. • Then restoring all these data in callback threads. • And then the GarbageCollector should clean all taken memory.
  19. 19. Async & Locking
  20. 20. Locking with Async / Await We could use Mutex or Semaphore for locking like this:
  21. 21. Locking with Async / Await Only the SemaphoreSlim supports an async lock for now:
  22. 22. Exceptions in async methods
  23. 23. Exceptions in async void We should not implement async void methods due to we never can catch their exceptions.
  24. 24. Handling exceptions in async And then we can log this way:Just one extension method:
  25. 25. Tricks & Hints
  26. 26. Thread contexts SynchronizationContext ExecutionContext SecurityContext CallContext, LogicalCallContext
  27. 27. Discarding the contexts We can prevent copying of thread context data: In async / await methods: For new threads:
  28. 28. Thread stack size IIS: In Windows Server 2008 and higher, the maximum stack size of a thread running on 32- bit version of IIS is 256 KB, and on an x64 server is 512 KB. Before, the max stack size of a thread in IIS equalled to 1 MB. Diminishing of a stack size can increase scalability and consequently performance of an application. For changing a stack size in Windows OS we can use editbin cmd utility like this:
  29. 29. Viewing a stack size The fragment of an output: To get information about stack size of your app, you can use dumpbin cmd utility: dumpbin /headers MyApp.exe > info.txt The 400000 is size in heximal value. So in decimal it equals to 4194304 bytes or 4 Mb
  30. 30. Closing Thoughts

×