├── .gitignore ├── LICENSE ├── README.md └── ThreadSafeObject ├── .editorconfig ├── TestNet45 ├── App.config ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── TestNet45.csproj └── packages.config ├── TestNetCore ├── Program.cs └── TestNetCore.csproj ├── TestObject ├── Calculation.cs └── TestObject.csproj ├── TestThreadSafe ├── Properties │ └── AssemblyInfo.cs ├── TestCalculationAdd.cs ├── TestCalculationAddDecrease.cs ├── TestCalculationField.cs ├── TestCalculationIndexer.cs ├── TestCalculationOperation.cs ├── TestCalculationProperty.cs ├── TestThreadSafe.csproj └── packages.config ├── ThreadSafeObject.sln └── ThreadSafeObject ├── ThreadSafe.cs └── ThreadSafeObject.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Andrei Ignat 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ThreadSafeObject 2 | Making any call to a function of an object thread safe 3 | NuGet Package at : 4 | https://www.nuget.org/packages/ThreadSafeObject/ 5 | 6 | The solution contain tests and 2 console project for .NET Core and .NET Framework 4.5.1 7 | 8 | The usage is pretty easy 9 | 10 | Let's say you have this 11 | 12 | ##### Calculation c = new Calculation(); 13 | 14 | ##### c.Add(); 15 | 16 | And you want 17 | 18 | ##### .Add 19 | 20 | to be thread safe 21 | 22 | In the Package Manager Console write: 23 | 24 | Install-Package ThreadSafeObject 25 | 26 | Then modify your code to: 27 | 28 | ##### Calculation c = new Calculation(); 29 | 30 | ##### dynamic ts = new ThreadSafe(c); 31 | 32 | ##### ts.Add(); 33 | 34 | 35 | More details at 36 | http://msprogrammer.serviciipeweb.ro/2017/07/10/making-any-call-to-a-function-of-an-object-thread-safe/ 37 | 38 | 39 | # Support this software 40 | 41 | This software is available for free and all of its source code is public domain. If you want further modifications, or just to show that you appreciate this, money are always welcome. 42 | 43 | [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/ignatandrei1970/25) 44 | 45 | * $5 for a cup of coffee 46 | * $10 for pizza 47 | * $25 for a lunch or two 48 | * $100+ for upgrading my development environment 49 | 50 | 51 | -------------------------------------------------------------------------------- /ThreadSafeObject/.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | end_of_line = crlf 3 | 4 | [*.xml] 5 | indent_style = space -------------------------------------------------------------------------------- /ThreadSafeObject/TestNet45/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestNet45/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using TestObject; 7 | using ThreadSafeObject; 8 | 9 | namespace TestNet45 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | int nrIterations = 100000; 16 | Calculation c = new Calculation(); 17 | dynamic ts = new ThreadSafe(c); 18 | List tasks = new List(); 19 | for (int i = 0; i < nrIterations; i++) 20 | { 21 | var t = new Task(() => ts.Add()); 22 | tasks.Add(t); 23 | } 24 | tasks.ForEach(t => t.Start()); 25 | Task.WaitAll(tasks.ToArray()); 26 | Console.WriteLine($"task iterations {nrIterations} result: {c.i}"); 27 | 28 | Console.WriteLine($"Field access: {ts.i}"); 29 | Console.WriteLine($"Property access: {ts.Value}"); 30 | Console.WriteLine($"Indexer access: {ts["key"]}"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestNet45/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TestNet45")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TestNet45")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e2cb9b76-1bde-4ee4-9bef-454119bd335d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestNet45/TestNet45.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {E2CB9B76-1BDE-4EE4-9BEF-454119BD335D} 8 | Exe 9 | TestNet45 10 | TestNet45 11 | v4.5.1 12 | 512 13 | true 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | {98e483c7-1434-46d3-8d6f-0cc72fec8f54} 56 | TestObject 57 | 58 | 59 | {063b19c1-956c-45e3-8091-0140c987d93f} 60 | ThreadSafeObject 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestNet45/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestNetCore/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using TestObject; 5 | using ThreadSafeObject; 6 | 7 | namespace TestNetCore 8 | { 9 | class Program 10 | { 11 | static void Main() 12 | { 13 | int nrIterations = 100000; 14 | Calculation c = new Calculation(); 15 | dynamic ts = new ThreadSafe(c); 16 | List tasks = new List(); 17 | for (int i = 0; i < nrIterations; i++) 18 | { 19 | var t = new Task(() => ts.Add()); 20 | tasks.Add(t); 21 | } 22 | tasks.ForEach(t => t.Start()); 23 | Task.WaitAll(tasks.ToArray()); 24 | Console.WriteLine($"task iterations {nrIterations} result: {c.i}"); 25 | 26 | Console.WriteLine($"Field access: {ts.i}"); 27 | Console.WriteLine($"Property access: {ts.Value}"); 28 | Console.WriteLine($"Indexer access: {ts["key"]}"); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /ThreadSafeObject/TestNetCore/TestNetCore.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp1.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestObject/Calculation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace TestObject 8 | { 9 | public class Calculation 10 | { 11 | public int i; 12 | 13 | public int Value 14 | { 15 | get { return i; } 16 | set { i = value; } 17 | } 18 | 19 | public int this[string key] 20 | { 21 | get { return i; } 22 | set { i = value; } 23 | } 24 | 25 | public int Add() 26 | { 27 | i++; 28 | return i; 29 | } 30 | 31 | public int Operation(int j) 32 | { 33 | i += j; 34 | return i; 35 | } 36 | 37 | public int Decrease() 38 | { 39 | i--; 40 | return i; 41 | } 42 | 43 | public int TwoOperations() 44 | { 45 | Add(); 46 | return Decrease(); 47 | } 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestObject/TestObject.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard1.2 5 | 6 | 7 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("TestThreadSafe")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("TestThreadSafe")] 10 | [assembly: AssemblyCopyright("Copyright © 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("b5ed6243-089c-4cab-b512-8f7291d8c885")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestCalculationAdd.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using ThreadSafeObject; 7 | using TestObject; 8 | 9 | namespace TestThreadSafe 10 | { 11 | [TestClass] 12 | public class TestCalculationAdd 13 | { 14 | [TestMethod] 15 | public void NotThreadSafeAdd() 16 | { 17 | int nrIterations = 100000; 18 | Calculation c = new Calculation(); 19 | List tasks = new List(); 20 | for (int i = 0; i < nrIterations; i++) 21 | { 22 | var t = new Task(() => c.Add()); 23 | tasks.Add(t); 24 | } 25 | tasks.ForEach(t => t.Start()); 26 | Task.WaitAll(tasks.ToArray()); 27 | Console.WriteLine("Result not thread safe" + c.i); 28 | Assert.AreNotEqual(nrIterations, c.i); 29 | } 30 | [TestMethod] 31 | public void ThreadSafeAdd() 32 | { 33 | int nrIterations = 100000; 34 | Calculation c = new Calculation(); 35 | dynamic ts = new ThreadSafe(c); 36 | List tasks = new List(); 37 | for (int i = 0; i < nrIterations; i++) 38 | { 39 | var t = new Task(() => ts.Add()); 40 | tasks.Add(t); 41 | } 42 | tasks.ForEach(t => t.Start()); 43 | Task.WaitAll(tasks.ToArray()); 44 | Assert.AreEqual(nrIterations, c.i); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestCalculationAddDecrease.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using TestObject; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using ThreadSafeObject; 7 | 8 | namespace TestThreadSafe 9 | { 10 | [TestClass] 11 | public class TestCalculationAddDecrease 12 | { 13 | [TestMethod] 14 | public void NotThreadSafeAddDecrease() 15 | { 16 | int nrIterations = 100000; 17 | Calculation c = new Calculation(); 18 | List tasks = new List(); 19 | for (int i = 0; i < nrIterations; i++) 20 | { 21 | var t = new Task(() => { 22 | c.TwoOperations(); 23 | c.Add(); 24 | return c.Decrease(); 25 | }); 26 | tasks.Add(t); 27 | } 28 | tasks.ForEach(t => t.Start()); 29 | Task.WaitAll(tasks.ToArray()); 30 | Console.WriteLine("Result not thread safe" + c.i); 31 | Assert.AreNotEqual(0, c.i); 32 | } 33 | [TestMethod] 34 | public void ThreadSafeAddDecrease() 35 | { 36 | int nrIterations = 100000; 37 | Calculation c = new Calculation(); 38 | dynamic ts = new ThreadSafe(c); 39 | List tasks = new List(); 40 | for (int i = 0; i < nrIterations; i++) 41 | { 42 | var t = new Task(() => 43 | { 44 | ts.TwoOperations(); 45 | ts.Add(); 46 | return ts.Decrease(); 47 | }); 48 | tasks.Add(t); 49 | } 50 | tasks.ForEach(t => t.Start()); 51 | Task.WaitAll(tasks.ToArray()); 52 | Assert.AreEqual(0, c.i); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestCalculationField.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using TestObject; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using ThreadSafeObject; 7 | 8 | namespace TestThreadSafe 9 | { 10 | [TestClass] 11 | public class TestCalculationField 12 | { 13 | [TestMethod] 14 | public void NotThreadSafeField() 15 | { 16 | int nrIterations = 100000; 17 | Calculation c = new Calculation(); 18 | List tasks = new List(); 19 | for (int i = 0; i < nrIterations; i++) 20 | { 21 | var t = new Task(() => c.i++); 22 | tasks.Add(t); 23 | } 24 | tasks.ForEach(t => t.Start()); 25 | Task.WaitAll(tasks.ToArray()); 26 | Console.WriteLine("Result not thread safe" + c.i); 27 | Assert.AreNotEqual(nrIterations, c.i); 28 | } 29 | [TestMethod] 30 | public void ThreadSafeField() 31 | { 32 | int nrIterations = 100000; 33 | Calculation c = new Calculation(); 34 | dynamic ts = new ThreadSafe(c); 35 | List tasks = new List(); 36 | for (int i = 0; i < nrIterations; i++) 37 | { 38 | var t = new Task(() => ts.i++); 39 | tasks.Add(t); 40 | } 41 | tasks.ForEach(t => t.Start()); 42 | Task.WaitAll(tasks.ToArray()); 43 | Assert.AreNotEqual(nrIterations, c.i); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestCalculationIndexer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using TestObject; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using ThreadSafeObject; 7 | 8 | namespace TestThreadSafe 9 | { 10 | [TestClass] 11 | public class TestCalculationIndexer 12 | { 13 | [TestMethod] 14 | public void NotThreadSafeIndexer() 15 | { 16 | int nrIterations = 100000; 17 | Calculation c = new Calculation(); 18 | List tasks = new List(); 19 | for (int i = 0; i < nrIterations; i++) 20 | { 21 | var t = new Task(() => c["key"]++); 22 | tasks.Add(t); 23 | } 24 | tasks.ForEach(t => t.Start()); 25 | Task.WaitAll(tasks.ToArray()); 26 | Console.WriteLine("Result not thread safe" + c["key"]); 27 | Assert.AreNotEqual(nrIterations, c["key"]); 28 | } 29 | [TestMethod] 30 | public void ThreadSafeIndexer() 31 | { 32 | int nrIterations = 100000; 33 | Calculation c = new Calculation(); 34 | dynamic ts = new ThreadSafe(c); 35 | List tasks = new List(); 36 | for (int i = 0; i < nrIterations; i++) 37 | { 38 | var t = new Task(() => ts["key"]++); 39 | tasks.Add(t); 40 | } 41 | tasks.ForEach(t => t.Start()); 42 | Task.WaitAll(tasks.ToArray()); 43 | Assert.AreNotEqual(nrIterations, c["key"]); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestCalculationOperation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using TestObject; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using ThreadSafeObject; 7 | 8 | namespace TestThreadSafe 9 | { 10 | [TestClass] 11 | public class TestCalculationOperation 12 | { 13 | [TestMethod] 14 | public void NotThreadSafeOperation() 15 | { 16 | int nrIterations = 100000; 17 | Calculation c = new Calculation(); 18 | List tasks = new List(); 19 | for (int i = 0; i < nrIterations; i++) 20 | { 21 | var t = new Task(() => c.Operation(2)); 22 | tasks.Add(t); 23 | } 24 | tasks.ForEach(t => t.Start()); 25 | Task.WaitAll(tasks.ToArray()); 26 | Console.WriteLine("Result not thread safe" + c.i); 27 | Assert.AreNotEqual(nrIterations*2, c.i); 28 | } 29 | 30 | [TestMethod] 31 | public void ThreadSafeOperation() 32 | { 33 | int nrIterations = 100000; 34 | Calculation c = new Calculation(); 35 | dynamic ts = new ThreadSafe(c); 36 | List tasks = new List(); 37 | for (int i = 0; i < nrIterations; i++) 38 | { 39 | var t = new Task(() => ts.Operation(2)); 40 | tasks.Add(t); 41 | } 42 | tasks.ForEach(t => t.Start()); 43 | Task.WaitAll(tasks.ToArray()); 44 | Assert.AreEqual(nrIterations*2, c.i); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestCalculationProperty.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using TestObject; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using ThreadSafeObject; 7 | 8 | namespace TestThreadSafe 9 | { 10 | [TestClass] 11 | public class TestCalculationProperty 12 | { 13 | [TestMethod] 14 | public void NotThreadSafeProperty() 15 | { 16 | int nrIterations = 100000; 17 | Calculation c = new Calculation(); 18 | List tasks = new List(); 19 | for (int i = 0; i < nrIterations; i++) 20 | { 21 | var t = new Task(() => c.Value++); 22 | tasks.Add(t); 23 | } 24 | tasks.ForEach(t => t.Start()); 25 | Task.WaitAll(tasks.ToArray()); 26 | Console.WriteLine("Result not thread safe" + c.Value); 27 | Assert.AreNotEqual(nrIterations, c.Value); 28 | } 29 | [TestMethod] 30 | public void ThreadSafeProperty() 31 | { 32 | int nrIterations = 100000; 33 | Calculation c = new Calculation(); 34 | dynamic ts = new ThreadSafe(c); 35 | List tasks = new List(); 36 | for (int i = 0; i < nrIterations; i++) 37 | { 38 | var t = new Task(() => ts.Value++); 39 | tasks.Add(t); 40 | } 41 | tasks.ForEach(t => t.Start()); 42 | Task.WaitAll(tasks.ToArray()); 43 | Assert.AreNotEqual(nrIterations, c.Value); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/TestThreadSafe.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {B5ED6243-089C-4CAB-B512-8F7291D8C885} 8 | Library 9 | Properties 10 | TestThreadSafe 11 | TestThreadSafe 12 | v4.5.2 13 | 512 14 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 15.0 16 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 17 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 18 | False 19 | UnitTest 20 | 21 | 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | 32 | 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE 37 | prompt 38 | 4 39 | 40 | 41 | 42 | 43 | ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll 44 | 45 | 46 | ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | {98e483c7-1434-46d3-8d6f-0cc72fec8f54} 63 | TestObject 64 | 65 | 66 | {063b19c1-956c-45e3-8091-0140c987d93f} 67 | ThreadSafeObject 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /ThreadSafeObject/TestThreadSafe/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /ThreadSafeObject/ThreadSafeObject.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.16 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestThreadSafe", "TestThreadSafe\TestThreadSafe.csproj", "{B5ED6243-089C-4CAB-B512-8F7291D8C885}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThreadSafeObject", "ThreadSafeObject\ThreadSafeObject.csproj", "{063B19C1-956C-45E3-8091-0140C987D93F}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestObject", "TestObject\TestObject.csproj", "{98E483C7-1434-46D3-8D6F-0CC72FEC8F54}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestNet45", "TestNet45\TestNet45.csproj", "{E2CB9B76-1BDE-4EE4-9BEF-454119BD335D}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestNetCore", "TestNetCore\TestNetCore.csproj", "{0F839E70-2D4D-44CA-9BBB-2DCEDE6AC01F}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1212EF97-3031-45A8-A6E0-BECDF0BCA215}" 17 | ProjectSection(SolutionItems) = preProject 18 | .editorconfig = .editorconfig 19 | EndProjectSection 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Release|Any CPU = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {B5ED6243-089C-4CAB-B512-8F7291D8C885}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {B5ED6243-089C-4CAB-B512-8F7291D8C885}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {B5ED6243-089C-4CAB-B512-8F7291D8C885}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {B5ED6243-089C-4CAB-B512-8F7291D8C885}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {063B19C1-956C-45E3-8091-0140C987D93F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {063B19C1-956C-45E3-8091-0140C987D93F}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {063B19C1-956C-45E3-8091-0140C987D93F}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {063B19C1-956C-45E3-8091-0140C987D93F}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {98E483C7-1434-46D3-8D6F-0CC72FEC8F54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {98E483C7-1434-46D3-8D6F-0CC72FEC8F54}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {98E483C7-1434-46D3-8D6F-0CC72FEC8F54}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {98E483C7-1434-46D3-8D6F-0CC72FEC8F54}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {E2CB9B76-1BDE-4EE4-9BEF-454119BD335D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {E2CB9B76-1BDE-4EE4-9BEF-454119BD335D}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {E2CB9B76-1BDE-4EE4-9BEF-454119BD335D}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {E2CB9B76-1BDE-4EE4-9BEF-454119BD335D}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {0F839E70-2D4D-44CA-9BBB-2DCEDE6AC01F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 44 | {0F839E70-2D4D-44CA-9BBB-2DCEDE6AC01F}.Debug|Any CPU.Build.0 = Debug|Any CPU 45 | {0F839E70-2D4D-44CA-9BBB-2DCEDE6AC01F}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {0F839E70-2D4D-44CA-9BBB-2DCEDE6AC01F}.Release|Any CPU.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | GlobalSection(SolutionProperties) = preSolution 49 | HideSolutionNode = FALSE 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /ThreadSafeObject/ThreadSafeObject/ThreadSafe.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Dynamic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace ThreadSafeObject 7 | { 8 | /// 9 | /// Making any call to a function thread safe 10 | /// Compatible .NET Standard 1.2 11 | /// Means .NET Framework>=4.5.1 12 | /// Means .NET Framework>=1.0 13 | /// Test and details at https://github.com/ignatandrei/ThreadSafeObject 14 | /// 15 | public class ThreadSafe: DynamicObject 16 | { 17 | private readonly object o; 18 | private readonly TypeInfo t; 19 | private readonly object myLock; 20 | 21 | /// 22 | /// Initializes a new instance of the class. 23 | /// 24 | /// 25 | /// The wrapped object whose operations will be made thread-safe. 26 | /// 27 | public ThreadSafe(object o) 28 | { 29 | this.o = o; 30 | t = o.GetType().GetTypeInfo(); 31 | myLock = new object(); 32 | } 33 | 34 | /// 35 | public override bool TrySetMember(SetMemberBinder binder, object value) 36 | { 37 | var prop = t.GetDeclaredProperty(binder.Name); 38 | if (prop != null) 39 | { 40 | lock (myLock) 41 | { 42 | prop.SetValue(o, value); 43 | } 44 | 45 | return true; 46 | } 47 | 48 | var field = t.GetDeclaredField(binder.Name); 49 | if (field != null) 50 | { 51 | lock (myLock) 52 | { 53 | field.SetValue(o, value); 54 | } 55 | 56 | return true; 57 | } 58 | 59 | return false; 60 | } 61 | 62 | /// 63 | public override bool TryGetMember(GetMemberBinder binder, out object result) 64 | { 65 | var prop = t.GetDeclaredProperty(binder.Name); 66 | if (prop != null) 67 | { 68 | lock (myLock) 69 | { 70 | result = prop.GetValue(o); 71 | } 72 | 73 | return true; 74 | } 75 | 76 | var field = t.GetDeclaredField(binder.Name); 77 | if (field != null) 78 | { 79 | lock (myLock) 80 | { 81 | result = field.GetValue(o); 82 | } 83 | 84 | return true; 85 | } 86 | 87 | result = null; 88 | return false; 89 | } 90 | 91 | /// 92 | /// Attempts to find the indexer property. 93 | /// 94 | /// 95 | /// The for the indexer property, if found; 96 | /// otherwise, . 97 | /// 98 | private PropertyInfo GetIndexedProperty() 99 | { 100 | // TODO: Is there a better way to do this? 101 | 102 | var prop = t.GetDeclaredProperty("Item"); 103 | if (prop == null || prop.GetIndexParameters().Length == 0) 104 | { 105 | prop = t.DeclaredProperties.FirstOrDefault(p => p.GetIndexParameters().Length != 0); 106 | } 107 | 108 | return prop; 109 | } 110 | 111 | /// 112 | public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) 113 | { 114 | var prop = GetIndexedProperty(); 115 | if (prop != null) 116 | { 117 | lock (myLock) 118 | { 119 | prop.SetValue(o, value, indexes); 120 | } 121 | 122 | return true; 123 | } 124 | 125 | return false; 126 | } 127 | 128 | /// 129 | public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) 130 | { 131 | var prop = GetIndexedProperty(); 132 | if (prop != null) 133 | { 134 | lock (myLock) 135 | { 136 | result = prop.GetValue(o, indexes); 137 | } 138 | 139 | return true; 140 | } 141 | 142 | result = null; 143 | return false; 144 | } 145 | 146 | /// 147 | public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) 148 | { 149 | var method = t.GetDeclaredMethod(binder.Name); 150 | if (method != null) 151 | { 152 | lock (myLock) 153 | { 154 | result = method.Invoke(o, args); 155 | } 156 | 157 | return true; 158 | } 159 | 160 | result = null; 161 | return false; 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /ThreadSafeObject/ThreadSafeObject/ThreadSafeObject.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard1.2 5 | True 6 | Andrei Ignat 7 | 8 | 9 | Makes any call to a function of an object thread safe 10 | https://github.com/ignatandrei/ThreadSafeObject 11 | https://github.com/ignatandrei/ThreadSafeObject 12 | GitHub 13 | Thread Safe 14 | Version 1 15 | 16 | 17 | 18 | True 19 | 20 | bin\Debug\netstandard1.2\ThreadSafeObject.xml 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | --------------------------------------------------------------------------------