Раскрывается тема проектирования и реализации многопоточных и асинхронных приложений для платформы .NET. Обсуждаются вопросы создания потоков, их дальнейшего использования и синхронизации в контексте масштабируемости и быстродействия. Рассматриваются общие ошибки и заблуждения при проектировании многопоточности, а также способы повышения производительности.
Salient Features of India constitution especially power and functions
.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование в .NET
1. Multithreading & Async programming in .Net
(Controversial topics and common mistakes)
Vladimir Kramar
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
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. 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. 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?
10. IAsyncResult – without callback Async / Await – with Task async method
IAsyncResult
(without callback)
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. 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:
14. Async – Why & Where?
Difference between Multithreading and Asynchronous programming:
Multithreading: Async (better approach):
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:
17. Async – Why & Where?
Why? – To increase scalability.
Where? – Whenever it is possible for long-running operations.
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.
27. Discarding the contexts
We can prevent copying of thread context data:
In async / await methods: For new threads:
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. 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