顯示具有 語法 標籤的文章。 顯示所有文章
顯示具有 語法 標籤的文章。 顯示所有文章

2020年2月2日 星期日

reference types(參考型別)在哪種狀況下不同變數會被彼此影響?

微軟官網文件
『With reference types, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable』
https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/types-and-variables
做了一個比較
Java也有同樣的特性,Java叫做Primitive Type (基本型態)、Class Type / Reference Type (類別型態 / 參考型態)
但是Java沒有struct類型(型別)

使用reference types(變數會被彼此影響)
https://dotnetfiddle.net/zURcCT


使用value types(變數不會被彼此影響)
https://dotnetfiddle.net/nNaCPE 


自己整理的C#和Java比較
https://hackmd.io/SVIGNsLLRkqYxywgJpcgTg

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:   } 
 

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/