Last active
February 23, 2016 16:58
-
-
Save jesuslpm/77b60126c8d787c7a76b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Threading; | |
| namespace ConsoleApplication1 | |
| { | |
| class Program | |
| { | |
| private static int count; | |
| static void Main(string[] args) | |
| { | |
| IWorker worker1 = new Worker1(); | |
| IWorker worker2 = new Worker2(); | |
| IWorker worker3 = new Worker3(); | |
| count = 100; | |
| RepeatWorker(worker1); | |
| RepeatWorker(worker2); | |
| RepeatWorker(worker3); | |
| var watch = System.Diagnostics.Stopwatch.StartNew(); | |
| count = 100000000; | |
| RepeatWorker(worker1); | |
| watch.Stop(); | |
| Console.WriteLine(watch.ElapsedMilliseconds); | |
| watch.Restart(); | |
| RepeatWorker(worker2); | |
| watch.Stop(); | |
| Console.WriteLine(watch.ElapsedMilliseconds); | |
| watch.Restart(); | |
| RepeatWorker(worker3); | |
| watch.Stop(); | |
| Console.WriteLine(watch.ElapsedMilliseconds); | |
| } | |
| private static void RepeatWorker(IWorker workeer) | |
| { | |
| for (int i = 0; i < count; i++) | |
| { | |
| workeer.DoWork(); | |
| } | |
| } | |
| } | |
| interface IWorker | |
| { | |
| void DoWork(); | |
| } | |
| class Worker1 : IWorker | |
| { | |
| private int isRunning = 0; | |
| public void DoWork() | |
| { | |
| if (Interlocked.CompareExchange(ref isRunning, 1, 0) == 0) | |
| { | |
| } | |
| } | |
| } | |
| class Worker2: IWorker | |
| { | |
| private volatile int isRunning = 0; | |
| public void DoWork() | |
| { | |
| if (isRunning == 0 && Interlocked.CompareExchange(ref isRunning, 1, 0) == 0) | |
| { | |
| } | |
| } | |
| private void DoTheMagic() | |
| { | |
| // do something interesting | |
| } | |
| } | |
| class Worker3 : IWorker | |
| { | |
| public void DoWork() | |
| { | |
| } | |
| private void DoTheMagic() | |
| { | |
| // do something interesting | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result is 777, 411, 343