background preloader

MultiThreading

Facebook Twitter

How to call a Visual C# method asynchronously. The Microsoft .NET Framework makes it easy to call functions asynchronously. Calling functions asynchronously causes the system to execute them in the background on a secondary thread while the calling function continues to do other work. In a typical (synchronous) function call, the function is executed right away on the same thread that made the call. The calling function waits for the call to complete and receives the results of the call before continuing. By contrast, when you make an asynchronous call, you retrieve the results of the asynchronous call later. This article demonstrates how to do this by using Visual C#.

Requirements How To Make Asynchronous Calls Asynchronous calls are made by using delegates. BeginInvoke() is used to initiate the asynchronous call. The EndInvoke() function is used to retrieve the results of the asynchronous call. The following is an example of a delegate and its BeginInvoke() and EndInvoke() methods: Sample 1: Calling A Method Synchronously. Avoiding And Detecting Deadlocks In .NET Apps with C# and C++ No More Hangs Advanced Techniques To Avoid And Detect Deadlocks In .NET Apps Joe Duffy Code download available at:Deadlocks.exe(188 KB) Application hangs are one of the most frustrating situations a user can experience.

They're terribly difficult to find before shipping, and even more difficult to debug after an application has been deployed. Unlike a crash, an application hang may not produce a crash dump or trigger custom failure logic. Users frequently shut down a frozen application before such information can be captured, meaning there's no tell-tale stack trace to help you find the source of the problem. Hangs can range from temporary to permanent. Engineering large concurrent applications using the standard Windows® shared-memory toolkit of threads and locks is significantly more involved than it might appear at first glance. Today's shared memory programming models require that the programmer think about the possible interleaving of instructions throughout program execution. Работа с потоками в C# Часть 1 Автор: Joseph AlbahariПеревод: Алексей КирюшкинИсточники: Threading in C# базируется на книгеJoseph Albahari Ben Albahari "C# 3.0 in a Nutshell"Материал предоставил: RSDN Magazine #1-2007 Опубликовано: 24.03.2007Исправлено: 20.06.2010Версия текста: 1.0 Благодарности Хотел бы поблагодарить Бена Албахари (Ben Albahari) из Microsoft Corporation и Джона Осборна (John Osborn) из O'Reilly Media, Inc. за их ценный вклад, а также Эрика Беднарца (Eric Bednarz) за его (до сих пор безотказный!)

Обход position:fixed-бага Internet Explorer. 1. Обзор и ключевые понятия C# поддерживает параллельное выполнение кода через многопоточность. Программа на C# запускается как единственный поток, автоматически создаваемый CLR и операционной системой (“главный” поток), и становится многопоточной при помощи создания дополнительных потоков. Вывод: В главном потоке создается новый поток t, исполняющий метод, который непрерывно печатает символ ‘y’. Консольный вывод: Как работает многопоточность Потоки vs. процессы.

Рекомендации по работе с потоками. Взаимоблокировки if (Monitor.TryEnter(lockObject, 300)) { try { // Place code protected by the Monitor here. } finally { Monitor.Exit(this); } } else { // Code to execute if the attempt times out. } Состояние гонки Многопроцессорные компьютеры Однопроцессорные компьютеры lock(lockObject) { myField++; } System.Threading.Interlocked.Increment(myField); if (x == null) { lock (lockObject) { if (x == null) { x = y; } } } System.Threading.Interlocked.CompareExchange(ref x, y, null); Основные понятия Другие ресурсы. Работа с потоками в C# Часть 2 Автор: Joseph AlbahariПеревод: Алексей КирюшкинThe RSDN GroupИсточники: Threading in C# базируется на книгеJoseph Albahari Ben Albahari "C# 3.0 in a Nutshell"Материал предоставил: RSDN Magazine #2-2007 Опубликовано: 27.06.2007Исправлено: 15.04.2009Версия текста: 1.0 3.

Работа с потоками Апартаменты и Windows Forms Потоковые апартаменты – это автоматический потокобезопасный режим, тесно связанный с COM, предыдущей технологией Microsoft. В то время как .NET в основном свободен от унаследованных потоковых моделей, временами они все еще необходимы, из-за потребности работать с устаревшими API. Апартамент – логический “контейнер” для потоков. Так же, как потоки, апартаменты могут содержать в себе объекты.

Вообразите себе библиотеку, где каждая книга представляет собой объект. Библиотека-контекст синхронизации позволит войти любому человеку, но только одному одновременно. Назначение типа апартамента Апартаменты никак не влияют на исполнение чистого .NET-кода. Control.Invoke BackgroundWorker.