Difference between revisions of "Coding Conventions"

From Agility
Jump to: navigation, search
(Multithreading)
(Ensure using thread safe data containers)
Line 33: Line 33:
  
  
===Ensure using thread safe data containers===
+
===Ensure using thread-safe data containers===
  
DataSets are not thread safe. If dataset is shared between threads than any update in such dataset mus be synchronized.
+
DataSets are not thread safe. If dataset is shared between threads and there is action which update dataset than any access to such dataset must be synchronized.
 +
 
 +
<pre>
 +
 
 +
static TranslateDataSet translateCache = new TranslateDataSet()
 +
static ReaderWriterLockSlim transLock = new ReaderWriterLockSlim();
 +
 
 +
function void updateCache(DataKey phraseKey, string phrase)
 +
{
 +
    lock(typeof(TranslateBO))
 +
    {
 +
        var phraseRow = translateCache.syPhrase.Find(phraseKey);
 +
        if(phraseRow != null)
 +
        {
 +
            phraseRow.Phrase = phrase;
 +
        }
 +
    }
 +
 
 +
}
 +
 
 +
</pre>

Revision as of 08:50, 24 January 2017


Multithreading

Critical sections should be small and predictable

To avoid dead-locks critical sections should be small enough to prove that dead lock is not possible. Critical section should not cover any complicated business task with access to database (for example business action).

Please AVOID below construction:

lock(typeof(TranslateBO))
{
    //Anti-pattern do not put complicated business functions (like get data by key) inside critical section
    transBO.getDataByKey(phraseKey);

    result = transBO.detailData.syPhrase.Find(phraseKey);
    [...]
}

In above example getDataByKey function is used inside critical section. It is NOT possible to prove that this function placed in critical section will never fall into dead-lock. Above example should be fixed with:

transBO.getDataByKey(phraseKey);
lock(typeof(TranslateBO))
{
    result = transBO.detailData.syPhrase.Find(phraseKey);
    [...]
}


Ensure using thread-safe data containers

DataSets are not thread safe. If dataset is shared between threads and there is action which update dataset than any access to such dataset must be synchronized.


static TranslateDataSet translateCache = new TranslateDataSet()
static ReaderWriterLockSlim transLock = new ReaderWriterLockSlim();

function void updateCache(DataKey phraseKey, string phrase)
{
    lock(typeof(TranslateBO))
    {
        var phraseRow = translateCache.syPhrase.Find(phraseKey);
        if(phraseRow != null)
        {
             phraseRow.Phrase = phrase;
        }
    }

}