Beginners Guide To Threading, C#, CodeProject, WPF

ThreadSafeObservableCollection

As part of an ongoing article I am just about to finish, I needed a thread safe ObservableCollection<T>. Now the native .NET framework doesn’t have one of those, but luckily it supplies you with the right job to create one using some of the Threading APIs.

Here is what I came up with.

 

   1:  /// <summary>
   2:  /// Provides a threadsafe ObservableCollection of T
   3:  /// </summary>
   4:  public class ThreadSafeObservableCollection<T>
   5:      : ObservableCollection<T>
   6:  {
   7:      #region Data
   8:      private Dispatcher _dispatcher;
   9:      private ReaderWriterLockSlim _lock;
  10:      #endregion
  11:  
  12:      #region Ctor
  13:      public ThreadSafeObservableCollection()
  14:      {
  15:          _dispatcher = Dispatcher.CurrentDispatcher;
  16:          _lock = new ReaderWriterLockSlim();
  17:      }
  18:      #endregion
  19:  
  20:  
  21:      #region Overrides
  22:  
  23:      /// <summary>
  24:      /// Clear all items
  25:      /// </summary>
  26:      protected override void ClearItems()
  27:      {
  28:          _dispatcher.InvokeIfRequired(() =>
  29:              {
  30:                  _lock.EnterWriteLock();
  31:                  try
  32:                  {
  33:                      base.ClearItems();
  34:                  }
  35:                  finally
  36:                  {
  37:                      _lock.ExitWriteLock();
  38:                  }
  39:              }, DispatcherPriority.DataBind);
  40:      }
  41:  
  42:      /// <summary>
  43:      /// Inserts an item
  44:      /// </summary>
  45:      protected override void InsertItem(int index, T item)
  46:      {
  47:          _dispatcher.InvokeIfRequired(() =>
  48:          {
  49:              if (index > this.Count)
  50:                  return;
  51:  
  52:              _lock.EnterWriteLock();
  53:              try
  54:              {
  55:                  base.InsertItem(index, item);
  56:              }
  57:              finally
  58:              {
  59:                  _lock.ExitWriteLock();
  60:              }
  61:          }, DispatcherPriority.DataBind);
  62:  
  63:      }
  64:  
  65:      /// <summary>
  66:      /// Moves an item
  67:      /// </summary>
  68:      protected override void MoveItem(int oldIndex, int newIndex)
  69:      {
  70:          _dispatcher.InvokeIfRequired(() =>
  71:          {
  72:              _lock.EnterReadLock();
  73:              Int32 itemCount = this.Count;
  74:              _lock.ExitReadLock();
  75:  
  76:              if (oldIndex >= itemCount |
  77:                  newIndex >= itemCount |
  78:                  oldIndex == newIndex)
  79:                  return;
  80:  
  81:              _lock.EnterWriteLock();
  82:              try
  83:              {
  84:                  base.MoveItem(oldIndex, newIndex);
  85:              }
  86:              finally
  87:              {
  88:                  _lock.ExitWriteLock();
  89:              }
  90:          }, DispatcherPriority.DataBind);
  91:  
  92:  
  93:  
  94:      }
  95:  
  96:      /// <summary>
  97:      /// Removes an item
  98:      /// </summary>
  99:      protected override void RemoveItem(int index)
 100:      {
 101:  
 102:          _dispatcher.InvokeIfRequired(() =>
 103:          {
 104:              if (index >= this.Count)
 105:                  return;
 106:  
 107:              _lock.EnterWriteLock();
 108:              try
 109:              {
 110:                  base.RemoveItem(index);
 111:              }
 112:              finally
 113:              {
 114:                  _lock.ExitWriteLock();
 115:              }
 116:          }, DispatcherPriority.DataBind);
 117:      }
 118:  
 119:      /// <summary>
 120:      /// Sets an item
 121:      /// </summary>
 122:      protected override void SetItem(int index, T item)
 123:      {
 124:          _dispatcher.InvokeIfRequired(() =>
 125:          {
 126:              _lock.EnterWriteLock();
 127:              try
 128:              {
 129:                  base.SetItem(index, item);
 130:              }
 131:              finally
 132:              {
 133:                  _lock.ExitWriteLock();
 134:              }
 135:          }, DispatcherPriority.DataBind);
 136:      }
 137:      #endregion
 138:  
 139:      #region Public Methods
 140:      /// <summary>
 141:      /// Return as a cloned copy of this Collection
 142:      /// </summary>
 143:      public T[] ToSyncArray()
 144:      {
 145:          _lock.EnterReadLock();
 146:          try
 147:          {
 148:              T[] _sync = new T[this.Count];
 149:              this.CopyTo(_sync, 0);
 150:              return _sync;
 151:          }
 152:          finally
 153:          {
 154:              _lock.ExitReadLock();
 155:          }
 156:      }
 157:      #endregion
 158:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

It relies on this small extension method

 

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }

   1:  /// <summary>
   2:  /// WPF Threading extension methods
   3:  /// </summary>
   4:  public static class WPFControlThreadingExtensions
   5:  {
   6:      #region Public Methods
   7:      /// <summary>
   8:      /// A simple WPF threading extension method, to invoke a delegate
   9:      /// on the correct thread if it is not currently on the correct thread
  10:      /// Which can be used with DispatcherObject types
  11:      /// </summary>
  12:      /// <param name="disp">The Dispatcher object on which to do the Invoke</param>
  13:      /// <param name="dotIt">The delegate to run</param>
  14:      /// <param name="priority">The DispatcherPriority</param>
  15:      public static void InvokeIfRequired(this Dispatcher disp,
  16:          Action dotIt, DispatcherPriority priority)
  17:      {
  18:          if (disp.Thread != Thread.CurrentThread)
  19:          {
  20:              disp.Invoke(priority, dotIt);
  21:          }
  22:          else
  23:              dotIt();
  24:      }
  25:      #endregion
  26:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }Hope it is useful to someone. Enjoy

Advertisements
C#

DateTimeOffSet Struct

Today I was asked something about a DateTime manipulation in SQL server, and one of my learned collegues piped up about a DateTimeOffset Type. Now I have never used or even heard of this, so looked it up and low and behold there is now a new DateTimeOffSet type in .NET 3.5, that is supposedly better for globalization issues.

There is a nice post about this over on the BCL team blog.

http://blogs.msdn.com/bclteam/archive/2007/06/14/datetimeoffset-a-new-datetime-structure-in-net-3-5-justin-van-patten.aspx

Enjoy

WPF

WPF : View Level Validation

I have just written a new article over at www.codeproject.com which talks about how to perform cross business object validation using a new idea that I had the other day. This technique is quite different from the standard IDataErrorInfo approach. The idea is that Each View is bound to a ViewModel, where the ViewModel may hold many business objects which may need some sort of cross validation.

As such each ViewModel is validated by a independent validator. You may want to read more about it over at http://www.codeproject.com/KB/WPF/GlobalWPFValidation.aspx

 

Enjoy

WPF

A Very Proud Moment (Well for me it was anyhow)

Today at work, my colleague and I decided we needed a graph control. And after about a day we came up with the following WPF control.

ticker

I think its pretty cool.  The low and high X-Axis points scale to suit the values Min/Max and the background changes shades according to the Mean of the values.

Now I should point out that we already had a free graph that this control has more than a passing resemblance to. The original graph was done by Andre de Cavaignac when he was at Lab49.

That said, we ended up using virtually none of the original code, apart from an attached property that changes the opacity based on the Mean of the values. The reason we decided to create our own is that the original graph was quite tied into Lab49 business, which did not suit our particular requirements. So bada bing, we knocked up this graph. I was very pleased with the results and it is done in only 2 classes. One is the graph and one contains the graph, and I think it is very easy to use.

I will hopefully be posting the code up soon over at www.codeproject.com, so if this floats your WPF boat, watch our for it over there soon.

Beginners Guide To Threading, C#, CodeProject, Lambdas / Anonomous delegates, WPF

Useful WPF Threading Extension Method

If you are working with WinForms or WPF you will more than likely run into some long running operation that you would like to run in a new thread. A novice may actually try and create a new Thread, which is ok, but that means you are responsible for the entire lifecycle of your new thread. Which gets tricky.

A better approach would be to use the ThreadPool or use a BackgroundWorker component which uses the ThreadPool beneath the surface.

However, even using these approaches the cardinal rule is that the control is owned by 1 thread, the thread that created the controls. That is typically the UI thread. So when you try and update the controls from a background thread you will run into problems.

This code demonstrates the problem with cross thread calls :

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Windows;
   6:  using System.Windows.Controls;
   7:  using System.Windows.Data;
   8:  using System.Windows.Documents;
   9:  using System.Windows.Input;
  10:  using System.Windows.Media;
  11:  using System.Windows.Media.Imaging;
  12:  using System.Windows.Navigation;
  13:  using System.Windows.Shapes;
  14:  using System.ComponentModel;
  15:  using System.Windows.Threading;
  16:  
  17:  namespace BackgroundThread
  18:  {
  19:  
  20:  
  21:      public partial class Window1 : Window
  22:      {
  23:          private Int32 currentCount = 0;
  24:          private Int32 maxCount = 500;
  25:          private float factor = 0;
  26:  
  27:          public Window1()
  28:          {
  29:              InitializeComponent();
  30:  
  31:          }
  32:  
  33:          private void btnGo_Click(object sender, RoutedEventArgs e)
  34:          {
  35:              factor = (float)100 / maxCount;
  36:  
  37:              BackgroundWorker bgWorker = new BackgroundWorker();
  38:              bgWorker.WorkerReportsProgress = true;
  39:              bgWorker.WorkerSupportsCancellation = false;
  40:  
  41:              //DoWork
  42:              bgWorker.DoWork += (s2, e2) =>
  43:              {
  44:                  for (currentCount = 0;
  45:                      currentCount < maxCount; currentCount++)
  46:                  {
  47:                      lstItems.Items.Add(
  48:                          String.Format("Count {0}", currentCount));
  49:                  }
  50:              };
  51:  
  52:              //ProgressChanged
  53:              bgWorker.ProgressChanged += (s3, e3) =>
  54:              {
  55:                  pgbar.Value = e3.ProgressPercentage;
  56:              };
  57:  
  58:              bgWorker.RunWorkerAsync();
  59:  
  60:          }
  61:      }
  62:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Which when run will result in the following:

crossThread

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

So how can we fix this, well we could use the Dispatcher.Invoke around the offending items, but perhaps a more elegant solution may be to use a extension method.

   1:  public static class WPFThreadingExtensions
   2:  {
   3:      /// <summary>
   4:      /// Simple helper extension method to marshall to correct
   5:      /// thread if its required
   6:      /// </summary>
   7:      /// <param name="control">The source control</param>
   8:      /// <param name="methodcall">The method to call</param>
   9:      /// <param name="priorityForCall">The thread priority</param>
  10:      public static void InvokeIfRequired(
  11:          this DispatcherObject control,
  12:          Action methodcall,
  13:          DispatcherPriority priorityForCall)
  14:      {
  15:          //see if we need to Invoke call to Dispatcher thread
  16:          if (control.Dispatcher.Thread != Thread.CurrentThread)
  17:              control.Dispatcher.Invoke(priorityForCall, methodcall);
  18:          else
  19:              methodcall();
  20:      }
  21:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Which we can then use in our code as simply as follows :

   1:      factor = (float)100 / maxCount;
   2:  
   3:      BackgroundWorker bgWorker = new BackgroundWorker();
   4:      bgWorker.WorkerReportsProgress = true;
   5:      bgWorker.WorkerSupportsCancellation = false;
   6:  
   7:      //DoWork
   8:      bgWorker.DoWork += (s2, e2) =>
   9:      {
  10:          for (currentCount = 0;
  11:              currentCount < maxCount; currentCount++)
  12:          {
  13:  
  14:              this.InvokeIfRequired(() =>
  15:              {
  16:                  lstItems.Items.Add(
  17:                      String.Format("Count {0}", currentCount));
  18:              },
  19:                  DispatcherPriority.Background);
  20:  
  21:              bgWorker.ReportProgress((int)(factor * (currentCount + 1)));
  22:  
  23:          }
  24:      };
  25:  
  26:      //ProgressChanged
  27:      bgWorker.ProgressChanged += (s3, e3) =>
  28:      {
  29:          this.InvokeIfRequired(() =>
  30:          {
  31:              pgbar.Value = e3.ProgressPercentage;
  32:          },
  33:          DispatcherPriority.Background);
  34:  
  35:  
  36:      };
  37:  
  38:      bgWorker.RunWorkerAsync();
  39:  
  40:  }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Which when run allows cross threaded calls to be marshaled to the correct Dispatcher object.

better

Hope this helps.
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

C#, LINQ

A simple SGML Parser and Visitor pattern loveliness

I am in the middle of so many article ideas right now that I am finding it hard to find enough time to look at them all, and some of them are pretty big articles. So what I have to do when this happens, is break them down into smaller areas, and look and see if any of the bigger articles would become clearer if I wrote it in smaller parts.

I am currently working on one that has to do with extending LINQ and the whole System.Linq.Expressions namespace idea in general. Now I don’t want to give too much away about what I will be doing, but one of the fundamental parts of how the whole System.Linq.Expressions namespace works, is by the use of the "Visitor Pattern".

If you have not used this pattern before, it is a structural pattern that can be used keep the algorithm separate from the object structure. I have used this pattern on a few different occasions and I for one really like it, though I do feel the standard visitor pattern could be improved a little.

I have written a small article talking about the standard a possibly improved visitor pattern over at www.codeproject.com, you can use the following link to read more.

http://www.codeproject.com/KB/recipes/ReflectVisitor.aspx

Enjoy