顯示具有 非同步 標籤的文章。 顯示所有文章
顯示具有 非同步 標籤的文章。 顯示所有文章

2019年12月15日 星期日

StringBuilder搭配lock達成Thread-Safe

C#沒有StringBuffer這個Thread-Safe 物件
還是可以透過搭配lock達成Thread-Safe 



https://www.sololearn.com/Discuss/657740/can-i-use-a-stringbuilder-in-a-parallel-foreachloop

lock(sb) { sb.Append(fruit).Append("!!").Append(fruit); }

C#
https://github.com/imrexhuang/HelloThreadStatic/blob/master/HelloThreadStatic/HelloThreadStatic/Program.cs 

 Java
https://gist.github.com/imrexhuang/df799e10868fed6d7ec94a7129160691 
 
http://developer.classpath.org/doc/java/lang/StringBuffer-source.html
 182:   public synchronized int length()
 183:   {
 184:     return count;
 185:   }
 
 
http://developer.classpath.org/doc/java/lang/StringBuilder-source.html
 173:   public int length()
 174:   {
 175:     return count;
 176:   } 
 

Threading in C#

http://www.albahari.com/threading/

Joseph Albahari
Threading in C# is from Chapters 21 and 22 of C# 4.0 in a Nutshell.

ThreadStatic

https://www.c-sharpcorner.com/article/overview-of-threadstatic-attribute-in-c-sharp/

Here, we initialized ThreadStatic field with 10. When we run it, only the main (first) thread’s field will be having 10. All the rest of the threads will have a default value of 0.


https://github.com/imrexhuang/HelloThreadStatic 


ThreadStaticAttribute 類別
https://docs.microsoft.com/zh-tw/dotnet/api/system.threadstaticattribute?view=netframework-4.8 


Using ThreadStatic and ThreadLocal
https://putridparrot.com/blog/using-threadstatic-and-threadlocal/