Posts

Showing posts from 2015

Coding Structure

Rules for Functions The function name should help indicate the function purpose. Functions should perform only one task. Functions should be as short as possible. Functions should control changes to internal data by restricting access. Each function must have an initial comment. Initial comments in the program should make the algorithm used in the function obvious. The initial comment should explain: What its purpose or use is. What arguments it requires or accepts and what their use is. What value(s) the function returns. What values or parts of the program the function may change. Algorithms used. Conditions which may cause the program to fail. The creator of the function. The date the function was created. The version number of the function. Comments in the code must be used frequently to ensure what is happening is easy to understand. Compound conditional statements should be limited to avoid confusion. When used in functions, the use of

How to lock a block containing await operation in C#

Save below code in a file say AsyncLock.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace namespaceName {     // http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266983.aspx     public class AsyncSemaphore     {         private readonly static Task s_completed = Task.FromResult(true);         private readonly Queue<TaskCompletionSource<bool>> m_waiters =new Queue<TaskCompletionSource<bool>>();         private int m_currentCount;         public AsyncSemaphore(int initialCount)         {             if (initialCount < 0) throw new ArgumentOutOfRangeException("initialCount");             m_currentCount = initialCount;         }         public Task WaitAsync()         {             lock (m_waiters)             {                 if (m_currentCount > 0)                 {                     --m_currentCount;