Concurrency

Threading.Timer vs. Timers.Timer

June 9, 2010 .NET, C#, Concurrency, Performance 6 comments

I agree that title doesn’t promise a lot of interesting stuff at first glance especially for experienced .net developers. But unless you encounter some issue due to incorrect usage of timers you will never think that root is in timers.

System.Threading.Timer vs. System.Windows.Forms.Timer

In few words what are differences between Threading and Forms timers just to start with something.
System.Threading.Timer executes some method on periodic bases. But what is interesting is that execution of method is performed in separate thread taken from ThreadPool. In other words it calls QueueUserWorkItem somewhere internally for your method at specified intervals.
System.Windows.Forms.Timer ensure as that execution of our method will be in the same thread where we’ve created timer.

What if operation takes longer than period?

Let’s now think what will happen if the operation we set for execution takes longer than interval.

When I have following code:

    internal class LearningThreadingTimer
    {
        private System.Threading.Timer timer;
        public void Run()
        {
            timer = new Timer(SomeOperation, null, 0, 1000);
        }
        private void SomeOperation(object state)
        {
            Thread.Sleep(500);
            Console.WriteLine(“a”);
        }
    }

my application behaves well – prints “a” twice a second. I took a look for number of threads in Task Manager and it stays constantly (7 threads).
Let now change following line: Thread.Sleep(500) to Thread.Sleep(8000). What will happen now? Just think before continue to read.
I’m almost completely sure that you predicted printing “a” every second after 8 seconds have passed. As you already guessed each of the “a” printings are scheduled in separate threads allocated from ThreadPool. So… amount of threads is constantly increasing… (Every 1.125 seconds :) )

Issue I’ve been investigating

Some mister X also figured out that Console.WriteLine(“a”) is critical and should run in one thread, at least because he is not sure how much does it take to execute Thread.Sleep(500). To ensure it will run in one thread he decided to have lock, like in code below:

    internal class LearningThreadingTimer
    {
        private System.Threading.Timer timer;
        private object locker = new object();
        public void Run()
        {
            timer = new Timer(SomeOperation, null, 0, 1000);
        }
        private void SomeOperation(object state)
        {
            lock (locker)
            {
                Thread.Sleep(8000);
                Console.WriteLine(“a”);   
            }
        }
    }

Yes, this code ensures that section under lock is executed in one thread. And you know this code works well unless your execution takes few hours and you will be out of threads and out of memory. :) So that is an issue I’ve been investigating.

My first idea was System.Windows.Forms.Timer

My first idea was to change this timer to the System.Windows.Forms.Timer, and it worked well in application, but that application is able to run in GUI and WinService modes. But there are so many complains over interned to do not use Forms.Timer for non UI stuff. Also if you put Forms.Timer into your console application it will simply not work.

Why System.Timers.Timer is good toy?

System.Timers.Timer is just wrapper over System.Threading.Timer, but what is very interesting is that it provides us with more developer-friendly abilities like enabling and disabling it.

My final decision which fixes issue is to disable timer when we are diving into our operation and enable on exit. In my app timer executes every 30 seconds so this could not be a problem. Fix looks like:

    internal class LearningTimersTimer
    {
        private System.Timers.Timer timer;
        private object locker = new object();
        public void Run()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += SomeOperation;
            timer.Start();
        }
        public void SomeOperation(object sender, EventArgs e)
        {
            timer.Enabled = false;
            lock (locker)
            {
                Thread.Sleep(8000);
                Console.WriteLine(“a”);
            }
            timer.Enabled = true;
        }
    }

And it looks that we don’t need lock there, but I left it there just to be sure is case if SomeOperation will be called from dozen of other threads.

MAKE DECISION ON TIMER BASING ON THIS TABLE (from msdn article)

System.Windows.Forms System.Timers System.Threading
Timer event runs on what thread? UI thread UI or worker thread Worker thread
Instances are thread safe? No Yes No
Familiar/intuitive object model? Yes Yes No
Requires Windows Forms? Yes No No
Metronome-quality beat? No Yes* Yes*
Timer event supports state object? No No Yes
Initial timer event can be scheduled? No No Yes
Class supports inheritance? Yes Yes No
* Depending on the availability of system resources (for example, worker threads

I hope my story is useful and when you will be searching like “C# Timer Threads issues” or “Allocation of threads when using timer” you will find my article and it will help you.


6 comments


AppDomain.UnhandledException and Application.ThreadException events

May 19, 2010 .NET, Concurrency, Fun No comments

Today I was playing with exception handling and threading in .NET. It was really fun.

Do you know guys that like to have everything in global try-catch block? I have two news for them.

Bad one

Exception will not be caught in try-catch block if it was thrown in another thread. Those guys also could think that Application.ThreadException could help them to catch those.

        [STAThread]
        static
void
Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
         
            Application.Run(new Form1());
        }

        static
void
Application_ThreadException(object
sender, System.Threading.ThreadExceptionEventArgs
e)
        {
            MessageBox.Show(“This is
something that I would not recommend you to have in your application.”
);
        }

But indeed this event fires only if exception has been thrown as result of Windows message or any other code that runs in same thread were your WinForms application lives. I tried to use two timers to verify that.
System.Windows.Forms.Timer – which ensures that code you have in your tick method runs in the same thread as your application. In this case I got message box.
System.Threading.Timer – which runs in separate thread, so my app just crashed.

But if those guys are writing all code in Form1.cs file… then maybe it worth for them to have handling of Application.ThreadException event :)

“Good” one

There is event which will be fired when exception is thrown from any code/thread withing your application domain. It is AppDomain.UnhandledException and it occurs when exception is not caught.

Lets take a look on code snippet that shows this:

        [STAThread]
        static
void
Main()
        {
            AppDomain currentDomain =
AppDomain.CurrentDomain;
            currentDomain.UnhandledException +=
currentDomain_UnhandledException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
         
            Application.Run(new Form1());
        }

        static
void
currentDomain_UnhandledException(object
sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(“This is
shown when ANY thread is thrown in ANY point of your Domain.”
);
        }

To test this I created Threading.Timer and fired it every 2 seconds and throwing exception on each tick, I put breakpoint into event. I got everything expected and application after that failed.

But one of our smart guys could guess to put Thread.Sleep(1000000); into handler code like below:

        static void currentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
        {
            Thread.Sleep(1000000); //
Try to guess what will happen

        }

Everyone is happy. Exception is thrown each 2 seconds or less and UI continue to respond. I hope you already see what is wrong with all of this.

This screenshot talks for itself:

 (My app already ate 705 threads and still eats…)

And as you know process could have up to 1024 threads. My process is not exclusion and it also crashed after reached that number.

Ok, looks like guys should change their mind.

Hope it was a bit fun.


No comments


Few threading performance tips I’ve learnt in recent time

May 16, 2010 .NET, Concurrency, MasterDiploma, Performance 4 comments

In recent time I was interacted with multithreading in .NET.
One of the intersting aspects of it is performance. Most of books says that we should not overplay with performance, because we could introduce ugly-super-not-catching bug. But since I’m using multithreading for my educational purposes I allow myself play with this.

Here is some list of performance tips that I’ve used:

1. UnsafeQueueUserWorkItem is faster than QueueUserWorkItem

Difference is in verification of Security Privileges. Unsafe version doesn’t care about privileges of calling code and runs everything in its own privileges scope.

2. Ensure that you don’t have redundant logic for scheduling your threads.

In my algorithm I have dozen of iterations on each of them I perform calculations on long list. So in order to make this paralleled I was dividing this list like [a|b|c|…]. My problem was in recalculating bounds on each iteration, but since list is always of the same size I could have calculating bounds once. So just ensure that don’t have such crap in your code.

3. Do not pass huge objects into your workers.

If you are using delegate ParameterizedThreadStart and pass lot of information with your param object it could decrease your performance. Slightly, but could. To avoid this you could put such information into some fields of the object that contains method for threading.

4. Ensure that you main thread is also busy guy!

I had this piece of code:

    for
(int i = 0; i < GridGroups;
i++)
    {
        ThreadPool.UnsafeQueueUserWorkItem(AsynchronousFindBestMatchingNeuron,
i);
    }
    for (int i = 0; i < GridGroups;
i++) DoneEvents[i].WaitOne();

Do you see where I have performance gap? Answer is in utilizing my main thread. Currently it is only scheduling some number of threads (GridGroups) to do some work and than it waits for them to accomplish. If we divide work to approximately equivalent partitions, we could gave some work to our main thread, and in this way waiting time will be eliminated.
Following code gives us persormance increase:

    for
(int i = 1; i < GridGroups;
i++)
    {
        ThreadPool.UnsafeQueueUserWorkItem(AsynchronousFindBestMatchingNeuron,
i);
    }
    AsynchronousFindBestMatchingNeuron(0);
    for (int i = 1; i < GridGroups;
i++) DoneEvents[i].WaitOne();

5. ThreadPool and .NET Framework 4.0

Guys, from Microsoft improved performance of the ThreadPool significantly! I just changed target framework of my project to the .Net 4.0 and for worst cases in my app got 1.5x time improvement.

What’s next?

Looking forward that I also could create more sophisticated synchronization with Monitor.Pulse() and Monitor.WaitOne().

Good Threading Reference

Btw: I read this quick book Threading in C#. It is very good reference if you would like to remind threading in C# and to find some good tips on sync approaches.

P.S. If someone is interested if I woke up at 8am. (See my previous post). I need to say that I failed that attempt. I woke at 12pm.


4 comments


Refactoring your code to be multithreaded

April 3, 2010 .NET, Concurrency No comments

In this post I will start with some time consuming algorithm, which is very simple and will move to decrease its execution time with using advantage of my two processors.

Time consuming algorithm

For example you have some complex calculations algorithm, which runs on array of dozens of elements. For simplicity let it be list of doubles like below:

      var
inputVector = new List<double>();
      for (int i = 0; i < 10000; i++)
        inputVector.Add(random.NextDouble());

All complex calculations that you do are located in class OneThreadAlgorithm. It goes through all array and gets index of the element, which is more closer to value d that you provide inside of method FindBestMatchingIndex.

  internal class OneThreadAlgorithm
  {
    public readonly List<double>
InputVector;
   
public OneThreadAlgorithm(List<double> inputVector)
    {
      InputVector = inputVector;
    }
    public int FindBestMatchingIndex(double d)
    {
      double
minDist = double.MaxValue;
      int bestInd
= -1;
      for (int i
= 0; i < InputVector.Count; i++)
      {
        var
currentDistance = DistanceProvider.GetDistance(InputVector[i],
d);
        if
(currentDistance < minDist)
        {
          minDist = currentDistance;
          bestInd = i;
 
      }
      }
 
    return bestInd;
    }
  }

If you are interested in DistanceProvider, it just returns between two double elements. Take a look on it.

  public static class
DistanceProvider
  {
    public static
double GetDistance(double val1, double
val2)
    {
     
for (int
i = 0; i < 10000; i++)i = i + 1 – 1;
      return Math.Abs(val1 – val2);
    }
  }

As you see I have some loop before returning value. It is needed to imitate hard calculations. I’m not using Thread.Sleep(), because there are some nuances, that will appear when we will move to multithreading, so I would I like to neglect them.

First change: dividing calculations to sections

As we see algorithm just loops through collection of values and finds some element. To make it going in few threads first we need to accommodate it. The intent of our accommodation is to divide calculations to sections, so we introduce following method

    public void FindBestMatchingIndexInRange(int start, int
end, double d)
    {
      double
minDist = double.MaxValue;
      int bestInd
= -1;
      for (int i
= start; i < end; i++)
      {
        var
currentDistance = DistanceProvider.GetDistance(InputVector[i],
d);
        if
(currentDistance < minDist)
        {
          minDist = currentDistance;
          bestInd = i;
 
      }
      }
      BestMatchingElements.Add(bestInd);
    }

So, what it does is the same that we had previously. Only the difference is that now we start searching for best matching indexes in range starting with index start and finishing with end, also we put result to the BestMatchingElements list. After we went through all sections we can find best matching element only in that list. See that below:

    public int FindBestMatchingIndex(double d)
    {
      double
minDist = double.MaxValue;
      int bestInd
= -1;
     
BestMatchingElements = new List<int>();
      int sectionLength = InputVector.Count /
ParallelingNumber;
      int start = 0;
      int end = sectionLength;
      for (int i = 0; i < ParallelingNumber; i++)
      {
       
FindBestMatchingIndexInRange(start, end, d);
        start = end;
   
    end += sectionLength;
        if (i == ParallelingNumber – 1) end =
InputVector.Count;
      }
      foreach (var
elementIndex in BestMatchingElements)
      {
        var currentDistance = DistanceProvider.GetDistance(InputVector[elementIndex],
d);
        if
(currentDistance < minDist)
        {
          minDist = currentDistance;
          bestInd = elementIndex;
        }
      }
      return bestInd;
 
  }

So now it works as well as before, theoretically it is a bit slower, and it does, especially when you divide array to lot of segments (number of segments we define with variable
ParallelingNumber
property).

Second modification: storing task information into one object

When we use multithreading we schedule method which represents public delegate void WaitCallback (Object state). So to accomplish this we create new class FindBestInRangeRequest and use it as an object that passes to changed method:

    public void FindBestMatchingIndexInRange(object bestInRangeRequest)

    {
      var request = (FindBestInRangeRequest)bestInRangeRequest;
      double minDist = double.MaxValue;
 
    int bestInd = -1;
      for (int i
= request.Start; i < request.End; i++)
   
  {

That new class FindBestInRangeRequest encapsulates Start, End, D and other values needed to schedule a threading task. See that class:

    internal class FindBestInRangeRequest
    {
      public int Start { get;
private set;
}
      public
int End { get;
private set;
}
      public
double D { get;
private set;
}
      public
ManualResetEvent Done { get; private
set; }
      public
FindBestInRangeRequest(int start, int end, double
d, ManualResetEvent
done)
      {
     
  Start = start;
        End = end;
        D = d;
       
Done = done;
      }
    }

As you see we are also passing the ManualResetEvent
object, which has method Set(), with using it we can identify that task execution has finished.

Third modification: Using ThreadPool

We can allocate threads manually, but that operation is very expensive, so it is strongly recommended to use ThreadPool.
So here is how we do use ThreadPool to call FindBestMatchingIndexInRange.

        var
bestInRangeRequest = new FindBestInRangeRequest(start,
end, d, DoneEvents[i]);
        ThreadPool.QueueUserWorkItem(FindBestMatchingIndexInRange,
bestInRangeRequest);

after we have scheduled all ranges we should ensure that all threads has synchronized. We could do this using

      WaitHandle.WaitAll(DoneEvents);

 method.
Another interesting thing is that saving into BestMatchingElements is not safe, so we use to unsure safe adding.

      Monitor.Enter(BestMatchingElements);
      BestMatchingElements.Add(bestInd);
      Monitor.Exit(BestMatchingElements);

which is the same to the locking with keyword lock.

Full code base of algorithm

  internal class MultiThreadAlgorithm
  {
    public int ParallelingNumber { get; private set; }
    private List<int>
BestMatchingElements { get; set; }
    private ManualResetEvent[] DoneEvents { get;
set; }
   
public readonly
List<double> InputVector;
    public
MultiThreadAlgorithm(List<double> inputVector, int parallelingNumber)
    {
      InputVector = inputVector;
      ParallelingNumber = parallelingNumber;
      DoneEvents = new
ManualResetEvent[ParallelingNumber];
    }
    public int FindBestMatchingIndex(double d)
    {
      double
minDist = double.MaxValue;
      int bestInd
= -1;
      BestMatchingElements = new List<int>();
     
for (int
i = 0; i < ParallelingNumber; i++)
      {
        DoneEvents[i] = new
ManualResetEvent(false);
      }
      int sectionLength = InputVector.Count /
ParallelingNumber;
      int start = 0;
      int end = sectionLength;
      for (int i = 0; i < ParallelingNumber; i++)
      {
        var bestInRangeRequest = new FindBestInRangeRequest(start,
end, d, DoneEvents[i]);
        ThreadPool.QueueUserWorkItem(FindBestMatchingIndexInRange,
bestInRangeRequest);
        start = end;
        end +=
sectionLength;
        if (i == ParallelingNumber – 1) end = InputVector.Count;
      }
      WaitHandle.WaitAll(DoneEvents);
      foreach (var elementIndex in
BestMatchingElements)
      {
        var
currentDistance = DistanceProvider.GetDistance(InputVector[elementIndex],
d);
        if
(currentDistance < minDist)
        {
          minDist = currentDistance;
          bestInd = elementIndex;
        }
      }
      return bestInd;
 
  }
    public void
FindBestMatchingIndexInRange(object
bestInRangeRequest)
    {
      var request
= (FindBestInRangeRequest)bestInRangeRequest;
      double
minDist = double.MaxValue;
      int bestInd
= -1;
      for (int i
= request.Start; i < request.End; i++)
   
  {
        var
currentDistance = DistanceProvider.GetDistance(InputVector[i],
request.D);
        if (currentDistance < minDist)
        {
          minDist =
currentDistance;
          bestInd = i;
        }
      }
      Monitor.Enter(BestMatchingElements);
      BestMatchingElements.Add(bestInd);
      Monitor.Exit(BestMatchingElements);
     
request.Done.Set();
    }
    internal class
FindBestInRangeRequest
    {
      public int
Start { get; private set; }
      public int End { get;
private set;
}
      public
double D { get;
private set;
}
      public
ManualResetEvent Done { get; private
set; }
      public
FindBestInRangeRequest(int start, int end, double
d, ManualResetEvent
done)
      {
     
  Start = start;
        End = end;
        D = d;
       
Done = done;
      }
    }
  }

Do you see how our class is cumbersome. So that is why do we call multithreading to be complex and not an easy to implement.

Does this pay off?
Of course, it does. I wrote this example, because I’ve been working on another, a bit more complex thing, but generally I did the same.

Here is output of execution of three variants of algorithm: simple, division to sections, multithreading.

One thread result = 9841. TIME: 0H:0M:2S:583ms
One thread with sections result = 9841. TIME: 0H:0M:2S:917ms
Multi threads result = 9841. TIME: 0H:0M:1S:939ms
Press any key to continue . . .

As could bee seen, multithreading variant is much-much faster. It could be even faster if I had more than two processors on my machine.


No comments


Simple example to see multithreading data sharing issues

March 23, 2010 .NET, Concurrency No comments

I heard a lot of the corruption that could be made by the multiple threads when they share same data. And understanding why that happen is not so hard, but I wanted some bright example of it, which will be able to quickly show what is going on.

So here is my example:

    public class Counter
    {
        public
int Count = 0;
        public
void UpdateCount()
        {
            for
(int i = 0; i < 10000; i++)
            {
                Count = Count + 1;
            }
        }
    }
    class Program
    {
        static
void Main(string[]
args)
        {
            var
counter = new Counter();
            var
threads = new Thread[500];
            for
(int i = 0; i < threads.Length;
++i)
            {
                threads[i] = new Thread(counter.UpdateCount);
                threads[i].Start();
            }
            foreach
(var thread in threads)
                thread.Join();
            Console.WriteLine(string.Format(
                @”If you are running this code on multiple processors machine you
probably will not get expected ThreadCount*Iterations={0}*{1}={2}, but
less number, which is currently equal to {3}”
,
                    threads.Length, 10000,
threads.Length * 10000, counter.Count));
        }
    }

As you see I’m using 500 threads. Why? First it is because this ensures that lot of them will be allocated on another processor and second is because the UpdateCount runs “Count = Count + 1” that is quite very trivial and requires about 3 atomic operations, so to increase possibility to run them in concurrent threads I increased their count.

Below is the output:

If you are running this code on multiple processors machine you probably will no
t get expected ThreadCount*Iterations=500*10000=5000000, but less number, which
is currently equal to 4994961
Press any key to continue . . .
As you see the actual number of the Count field is less than expected. We lost one each time when next happens at once:
Thread 1: Reads Count (1000)
Thread 2: Reads Count (1000)
Thread 1: Increases Count (1001)
Thread 2: Increases Count (1001)
Thread 1: Writes Count (1001)
Thread 2: Writes Count (1001) – he-he so it wrote back the same number, not 1002
You probably already know how to solve this with lock or Interlocked class or other stuff.
For example just change line Count = Count + 1; with line Interlocked.Increment(ref Count); or lock (this)Count = Count + 1; But I’m getting fun writing this.


No comments


Multithreading in CLR

March 14, 2010 .NET, C#, Concurrency No comments

Here I have code that provides some explanations to the multithreading in .NET. Wrote it to refresh what I know on concurrency.

    1 /********************************************************
    2  *
    3  *                CODE IS MY PRESENTATION
    4  *
    5  ********************************************************/
    6 using System;
    7 using System.IO;
    8 
    9 //1. CLR threading is based on Windows threading.
   10 //2. CLR threading is going away from correspondence with Windows threading.
   11 //SO do not use native windows functions if you already writing CLR code
   12 //that is for future, of course Microsoft is not sleeping
   13 
   14 //Let’s start
   15 //This is namespace where Multithreading lives…
   16 using System.Threading;
   17 
   18 namespace TheoryConsole
   19 {
   20     class Program
   21     {
   22         static void Main(string[] args)
   23         {
   24             MultiThreadingInCLR presentation = new MultiThreadingInCLR();
   25 
   26             //presentation.CLRHasPoolOfThreads();
   27             //presentation.UsingThreadPoolForAsynchCalculations();
   28             //presentation.UsingDedicatedThread();
   29             //presentation.PeriodicalCallinOfAsynchOperations();
   30             presentation.AsynchronousProgrammingModel();
   31 
   32             Thread.Sleep(100);
   33             //Console.WriteLine(“Press any key to exit…”);
   34             //Console.ReadLine();
   35         }
   36     }
   37 
   38     public class MultiThreadingInCLR
   39     {
   40         //Many developers uses multithreading too often,
   41         //but it is not cheap.
   42 
   43         //Because
   44         //to Switch context system needs:
   45         // – go to core -> save processor registers ->
   46         // put spin-blocker -> take another thread ->
   47         // unput blocker -> load registers > run thread
   48 
   49         //Pool of Threads
   50         public void CLRHasPoolOfThreads()
   51         {
   52             //Each Process has its oun Pool wich can be used
   53             // in all AppDomains of that Process
   54             ThreadPool.QueueUserWorkItem(DoAsynchWork, 10);
   55 
   56             //If there are no requests to Pool,
   57             //CLR will delete threads from it in about 2 minutes
   58 
   59             // Amount of threads in Pool
   60             // – Do not try to limit amount of threads in Pool
   61             // There are two types of threads: Worker and I/O
   62             int workingThreads = 0;
   63             int completionThreads = 0;
   64             //Get/Set Max/Min Threads
   65             ThreadPool.GetMaxThreads(out workingThreads, out completionThreads);
   66 
   67             //To GetAvailableThreads call it:
   68             //ThreadPool.GetAvailableThreads();
   69 
   70             for (int i = 0; i < 506; i++)
   71             {
   72                 ThreadPool.QueueUserWorkItem(DoAsynchWork, 100);
   73             }
   74 
   75             ThreadPool.GetMaxThreads(out workingThreads, out completionThreads);
   76             workingThreads = 1000;
   77         }
   78 
   79 
   80         public void UsingThreadPoolForAsynchCalculations()
   81         {
   82             //If you do not need I/O operations use Worker type of thread
   83             //For example spell-checker in some editor need to work asynchronously
   84             //
   85             //Most commonly these three methods are called:
   86             //
   87             //static Boolean QueueUserWorkItem(WaitCallback callBack);
   88             //static Boolean
   89             //   QueueUserWorkItem(WaitCallback callBack, Object state);
   90             //static Boolean
   91             //   UnsafeQueueUserWorkItem(WaitCallback callBack, Object state);
   92 
   93             //callBack is delegate with the next signature:
   94             //delegate void WaitCallBack(Object state);
   95             WaitCallBackExample_IDoHardWork(null);
   96 
   97             //Here is how to start doing hard work asynchromously
   98             ThreadPool.QueueUserWorkItem(WaitCallBackExample_IDoHardWork);
   99 
  100             //Use UnsafeQueueUserWorkItem if the time resource is very critical
  101             //Reason: QueueUserWorkItem is verifying
  102             // if the assemblies from Thread stack has permissions
  103             // to access file for example
  104             //SecurityException could be generated if there is no presmissions
  105         }
  106 
  107         #region Dedicated Thread
  108         public void UsingDedicatedThread()
  109         {
  110             //Commonly is used if we need to set some priority to thread
  111             // or if we need to change other properties of Thread
  112             // – we need set some properties to the thread
  113             // – we need set priority to our thread
  114             //        (ThreadPool has one priority for all threads in it)
  115             // – if we want run Thread in foreground
  116             //        (ThreadPoole runs threads in background)
  117 
  118             //please note that here we do NOT create actual thread,
  119             // because thread will be created only
  120             //when we will call our thread object
  121             Thread someNewThread = new Thread(ComputeBoundWork);
  122             //When we call Start method actuall thread is created
  123             // and process starts
  124 
  125             someNewThread.Start(1);
  126             Thread.Sleep(1000);//this imitates some work in main thread
  127 
  128             //Please note!
  129             // that after ComputeBoundWork finished its work,
  130             // actual system thread was deleted
  131 
  132             // this waits while the dedicated thread will finish all its work…
  133             someNewThread.Join();
  134 
  135             // so this is some kind of sysnch of threads..
  136         }
  137         #endregion
  138 
  139         #region Timer
  140         public void PeriodicalCallinOfAsynchOperations()
  141         {
  142             //System.Threading namespace has Timer defined
  143             //it has 4 very similar constructors
  144             //this used only TimerCallback
  145             //Timer timer1 = new Timer(ComputeBoundWork);
  146             Timer timer2 = new Timer(ComputeBoundWork, null, 0, 1000);
  147             // method will be called only once
  148             //Timer timer3 =
  149             //  new Timer(ComputeBoundWork, null, 0, Timeout.Infinite);
  150 
  151             //if you want to change timing behaviour of the timer
  152             // you could use Change() method, or Dispose() to stop…
  153             Thread.Sleep(10000);// this imitates some work here – 10 seconds
  154             timer2.Dispose();
  155 
  156             // Please note that there are 3 different Timers in FCL
  157             // – System.Threading.Timer
  158             //      is most suitable for doing asynch operations
  159             // – System.Windows.Forms.Timer
  160             //      is equivalent to WinAPI SetTimer.. events are added WM_TIMER
  161             // – System.Timers.Timer
  162             //      is some kind of wrapper of the Threading.Timer
  163         }
  164         #endregion
  165 
  166         #region Asynchronous Programming Model
  167 
  168         private IAsyncResult synchResultForFileWriting;
  169         private FileStream fs;
  170         public void AsynchronousProgrammingModel()
  171         {
  172             // Using of the asynchronous operations is the key to big programms :)
  173             // Combination of it with the ThreadPool
  174             //  is way to effectively use all processors of the system.
  175             // Examples where it is used…
  176             // – System.IO.Stream -> FileStream and NetworkStream
  177             //        derived classes has methods BeginRead(), BeginWrite()
  178             // – System.Net.Dns -> BeginGetHostAddresses(),
  179             //        BeginGetHostByName(), and so on…
  180             // – System.Net.Sockets -> BeginAccept(), BeginConnect(), …
  181             // all delegate types has BeginInvoke(), what could be used in APM
  182 
  183             //ok let we see file reading example
  184             fs = new FileStream(
  185                 “test.bin”, FileMode.OpenOrCreate,
  186                 FileAccess.Write, FileShare.None, 35000, FileOptions.Asynchronous);
  187             synchResultForFileWriting =
  188                 fs.BeginWrite(new byte[32738], 0, 32000, CallBackMethod, null);
  189             Console.WriteLine(
  190                 “This is called just after we said to write something to file.”);
  191 
  192 
  193             // There are 3 types of joining threads.. im APM
  194             // 1. Waiting for finish of work
  195             //Int32 readMeFile.EndRead(IAsyncResutl asyncResult)
  196 
  197             // 2. Regualar polling – is not effective method
  198             Stream readMeFile = new FileStream(“film.mp4”, FileMode.Open,
  199                   FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous);
  200 
  201             byte[] fileContent = new byte[450000000];
  202             IAsyncResult ar =
  203                 readMeFile.BeginRead
  204                     (fileContent, 0, fileContent.Length, null, null);
  205 
  206             while (!ar.IsCompleted)
  207             {
  208                 Console.WriteLine(
  209                     “Reading Large Music file operation is not completed…”);
  210                 Thread.Sleep(100);
  211             }
  212 
  213             //please note that this will not stop actuall
  214             //     thread because we were asking for finish above
  215             readMeFile.EndRead(ar);
  216             Console.WriteLine(“We already finished reading large music file.”);
  217 
  218             // 3. Callback!!
  219             // is the most efficient and commonly used joining type
  220         }
  221 
  222         private void UserAlreadyWantsToReadThatFile()
  223         {
  224             fs.EndWrite(synchResultForFileWriting);
  225             //now we are sure that ansynch writing to file has finished its work!!
  226             fs.Close();
  227         }
  228 
  229 
  230         private void CallBackMethod(IAsyncResult ar)
  231         {
  232             //this method will be called when writing to file will finish its work
  233             Console.WriteLine(“We just finished writing to file…”);
  234         }
  235 
  236         #endregion
  237 
  238         public void WaitCallBackExample_IDoHardWork(object hardParameter)
  239         {
  240             //actually if you see my body you know that I do not do work
  241             // I sleep for 2 seconds :)
  242             Thread.Sleep(2000);
  243         }
  244 
  245         public void DoAsynchWork(object miliseconds)
  246         {
  247             Thread.Sleep((int)miliseconds);
  248         }
  249 
  250         public void ComputeBoundWork(object opCode)
  251         {
  252             Thread.Sleep(1000);// this imitates some work…
  253             Console.WriteLine(
  254                 string.Format(“Compuing bound work with param: {0}”, opCode));
  255         }
  256     }
  257 }


No comments