Hi there!
I have recently published post in OzCode blog describing common debugging mistakes and some suggestions how to solve them. Hope you will enjoy reading it.
Happy coding!
.Net C# ... technologies, design, news, code samples and thoughts
Hi there!
I have recently published post in OzCode blog describing common debugging mistakes and some suggestions how to solve them. Hope you will enjoy reading it.
Happy coding!
public class MyVisitor{public void Visit(SomeObjectA a){// Algorithm comes here
}public void Visit(SomeObjectB b){// Algorithm comes here
}}
public class MySomeObjectAVisitor : IVisitor<SomeObjectA>{public void Visit(SomeObjectA a){// Algorithm comes here
}}public class MySomeObjectBVisitor : IVisitor<SomeObjectB>{public void Visit(SomeObjectB b){// Algorithm comes here
}}
{public override void Accept(IVisitor visitor){// Coupling
if (visitor is IVisitor<MySomeObject>){// Casting
((IVisitor<MySomeObject>)visitor).Visit(this);
}}}
public abstract class Shape{}public class Box : Shape{public double Side { get; set; }}
public class Canvas : Shape, IEnumerable<Shape>{private readonly List<Shape> _shapes = new List<Shape>();public double Height { get; set; }public double Width { get; set; }public void Add(Shape s){_shapes.Add(s);}public IEnumerator<Shape> GetEnumerator()
{return _shapes.GetEnumerator();
}IEnumerator IEnumerable.GetEnumerator(){return GetEnumerator();
}}
public interface IVisitor<in T>{void Visit(T to);
}
This one is simple, giving Box instance we can call some magic operation on IGraphics interface which will draw the data on the device. Nice things starts here where it is needed to iterate on shapes inside the canvas:class BoxDrawVisitor : IVisitor<Box>
{private readonly IGraphics _graphics;public BoxDrawVisitor(IGraphics graphics)
{_graphics = graphics;}public void Visit(Box to){_graphics.DrawBox(to.Side);}public void Dispose(){}}
Basically, canvas is an composition of shapes, and it is necessary to visit all of them. It may end up with coupling of different visitors implementations. To prevent it IVisitor<Shape> is introduced here. It’s kind of “abstract” visitor which should know which concrete visitor should be used based on the concrete type of the shape we got in the foreach loop. This “abstract” visitor is the resolution of the problem, so how it can be implemented? Before going there let’s see how this concept can be used in this Unit Test as an example:class CanvasDrawVisitor : IVisitor<Canvas>
{private readonly IGraphics _graphics;private readonly IVisitor<Shape> _visitor;public CanvasDrawVisitor(IVisitor<Shape> visitor, IGraphics graphics)
{_visitor = visitor;_graphics = graphics;}public void Visit(Canvas to){_graphics.DrawRectangle(to.Height, to.Width);foreach (Shape shape in to){shape.Accept(_visitor);}}public void Dispose(){}}
To apply some operation one can resolve visitor from the container which is capable to deal with virtually any shape while its concrete visitor is registered within the container. I decided to use registration names to distinguish visitors for the same objects but implementing different functionality:[TestMethod]public void TestDrawBox(){Box b = new Box {Side = 5};
IVisitor<Shape> visitor = _container.Resolve<IVisitor<Shape>>("Draw");
b.Accept(visitor);A.CallTo(() => _graphics.DrawBox(5)).MustHaveHappened();}
[TestMethod]public void TestDrawBox(){Box b = new Box {Side = 5};
IVisitor<Shape> visitor = _container.Resolve<IVisitor<Shape>>("Draw");
b.Accept(visitor);A.CallTo(() => _graphics.DrawBox(5)).MustHaveHappened();}
Every time IVisitor<Shape> will be resolved on the unity container AbstractVisitor<Shape> instance will be created with current build context and this instance will be added to the resolution context to prevent creation of additional instance in case some class implementation depends on IVisitor<Shape>. This is the case for CanvasDrawVisitor for example. Thus, going back to the test above, the resolution linepublic class VisitorContainerExtension<T> : UnityContainerExtension{protected override void Initialize(){Context.Strategies.AddNew<VisitorBuilderStrategy<T>>(UnityBuildStage.PreCreation);}}internal class VisitorBuilderStrategy<T> : BuilderStrategy{public override void PreBuildUp(IBuilderContext context){Type typeToBuild = context.BuildKey.Type;if (typeToBuild.IsGenericType && typeof (IVisitor<>).MakeGenericType(typeof(T)) == typeToBuild){AbstractVisitor<T> abstractVisitor = new AbstractVisitor<T>(context);
context.Existing = abstractVisitor;context.AddResolverOverrides(new DependencyOverride(typeToBuild, abstractVisitor));
}}}
IVisitor<Shape> visitor = _container.Resolve<IVisitor<Shape>>("Draw");
Here Visit method receives the concrete shape type which should be visited. The only thing AbstractVisitor should do is to resolve the registered concrete visitor implementation, like BoxDrawVisitor for instance, and delegate Visit call to the concrete visitor. For that meter concrete visitor type is constructed and then build context is used for construction which will preserve all ResolveOverride that you may provide to the initial resolve method call, like in test below. It is important to mention that initial BuildKey.Name is reused to resolve concrete visitors.class AbstractVisitor<T> : IVisitor<T>
{private readonly IBuilderContext _context;public AbstractVisitor(IBuilderContext context)
{_context = context;}public void Visit(T to){Type concreteShapeType = to.GetType();// Construct generic visitor type for concrete shape type
Type concreteVisitorType = typeof(IVisitor<>).MakeGenericType(concreteShapeType);
object concreteVisitor = _context.NewBuildUp(new NamedTypeBuildKey(concreteVisitorType, _context.BuildKey.Name));try
{// Invoke
concreteVisitorType.InvokeMember("Visit", BindingFlags.InvokeMethod, null, concreteVisitor, new object[] { to });}catch(TargetInvocationException ex)
{throw ex.InnerException;
}}public void Dispose(){}}
[TestMethod]public void TestMagnifyAndThenDrawCircle(){Circle c = new Circle {Radius = 5};
var magnificationVisitor = _container.Resolve<IVisitor<Shape>>("Magnify", new ParameterOverride("ratio", 2D));var drawVisitor = _container.Resolve<IVisitor<Shape>>("Draw");
c.Accept(magnificationVisitor, drawVisitor);A.CallTo(() => _graphics.DrawCircle(10)).MustHaveHappened();}
Recently I had some mess with resources leak in some .Net system that was caused by miss use of IDisposable objects.
In this post you can find brief summary of disposable objects use cases. Hope it will help to write better code.
public void ReadYourPart(Stream data){// Read from stream// And leave it opened, do not dispose it}
In this case I would like to consider function that receives some disposable resource as parameter, stream in example above. Since it is impossible to know the scope where this resource must be available you don’t want to dispose it. Just live it alone when you finished.
If you have to write class with disposable member you must add implementation of IDisposable interface to your class.
public class MyClass : IDisposable{private IDisposable resource;public MyClass(IDisposable resource){this.resource = resourse;}
…
}
Here responsibility to dispose the resource is delegated to the user of MyClass via it dispose method.
And finally if you instantiating IDisposable so you are responsible to dispose it. And of course the best way to use using clause.
using (Stream data = new FileStream("data.dat", FileMode.Open)){// dara usage comes here}
I would also call dispose for resource returned by some function like in example below:
using (IDisposable someResource = factory.OpenResource()){// resource usage comes here}
Happy coding!
Another item in list of newly added threading primitives in .Net 4.0 is a Task. It represents asynchronous operation which execution is controlled by TaskScheduler. In this post I will try to analyze task and scheduler capabilities.
First of all lets look how can we use Task. For this propose I changed some code from previous post to use Task instead of thread pool mechanism:
Lines 8-10 creates and schedules three tasks each of them will execute Worker function. First difference is that task is initialized by Action or Func<TResult> delegates in opposite to thread pool WaitCallBack delegate. It means that there are two types of tasks: first one initialized by Action that does it work and does not returns any values, and another one initialized by Func<TResult> that will return some value. Thus, if task is initialized by Func<TResult> new instance of Task<TResult> is created which contains Result property. When task is finished value returned by Func delegate will be stored in the task and can be obtained from Result property. Both types of tasks contains Exception property that will store an exception thrown by the worker delegates. If exception is not thrown Exception property will return null.
Next important tasks feature is synchronization. Task contains two static methods WaitAll and WaitAny that acts exactly like WaitHandle.WaitAll and WaitHandle.WaitAny. That means that there is built-in tasks synchronization mechanism. Line 12 shows how it is simple to block until all executed functions are finished.
So, let’s understand what happens when task is started, by StartNew function for example. Task execution is controlled by TaskScheduler associated to current synchronization context. Actually task scheduler is an abstract class and it is up to its implementation to decide how task will be executed.
protected internal abstract void QueueTask(Task task)
When new task is started task scheduler QueueTask method is called. Now scheduler have to decide what to do. Default scheduler will execute tasks in same manner as thread pool did it before. But now task scheduler can be replaced by user implementation. There is good sample in MSDN, showing dedicated thread pool implementation which executes all queued tasks turn by turn in one thread.
Task provides very comfortable and tunable parallel programming mechanism. However it is important to note that user can’t assume that Task he executes will really run in parallel. That's why it is very bad idea to block task execution in any way, i.e. lock or wait. The best practice to use task for any independent operation that doesn’t need to access any shared resources.
This post starts the series of .Net Framework 4.0 and C# 4.0 new features reviews. Since I working a lot with concurrency, I choose to start from System.Threading base class library. Framework 4.0 will contain many useful threading tools, one of them is Barrier class.
Assume that you have to implement algorithm which can be divided into series of independent phases where result of each will be used by next one. That means next algorithm phase can not be started before previous one is finished. These days almost every desktop have at least two cores, so it can be good idea to add concurrency to phase computation. If this scenario looks familiar, you will be glad to hear that now is will be pretty easy to synchronize between concurrent phases by using Barrier class.
Next code snippet contains Barrier usage example. Here barrier is used to synchronize between three worker threads. In constructor it is possible to specify how much participants barrier will synchronize and provide handler that will be executed after each phase is completed. When phase is completed worker signals to the barrier and waits until all workers are done. When number of phases worker have to participate is over it is possible to notify barrier that worker is no longer participating by calling RemoveParticipant method.
public class WorkerInfo
{
public int WorkTime { get; set; }
public int ParticipiantPhaces { get; set; }
public string Name { get; set; }
public Barrier Barrier { get; set; }
}
public class BarrierTest
{
public void Test()
{
ManualResetEventSlim ev = new ManualResetEventSlim(false);
Barrier barrier = new Barrier(3, b =>
{
Console.WriteLine("Phase {0} completed", b.CurrentPhaseNumber);
if (b.CurrentPhaseNumber >= 3) ev.Set();
});
ThreadPool.QueueUserWorkItem(Worker, new WorkerInfo
{
WorkTime = 400,
Name = "First",
ParticipiantPhaces = 4,
Barrier = barrier
});
ThreadPool.QueueUserWorkItem(Worker, new WorkerInfo
{
WorkTime = 600,
Name = "Second",
ParticipiantPhaces = 3,
Barrier = barrier
});
ThreadPool.QueueUserWorkItem(Worker, new WorkerInfo
{
WorkTime = 500,
Name = "Third",
ParticipiantPhaces = 2,
Barrier = barrier
});
// No direct way to syncronize with barrier
// It may be good idea to add barrier.WaitForZeroParticipiants(timeout)
ev.Wait();
Console.ReadLine();
}
private void Worker(object state)
{
WorkerInfo info = state as WorkerInfo;
for (int i = 0; i < info.ParticipiantPhaces; i++)
{
// Do the work
Thread.Sleep(info.WorkTime);
Console.WriteLine("{0} done.", info.Name);
info.Barrier.SignalAndWait();
}
info.Barrier.RemoveParticipant();
}
}
OK, phases are separated and workers are synchronized.
It can be good idea to add method to wait until all participants will finish and eliminate ManualResetEvent usage.
It runs pretty fast for beta software. After clicking on almost every button it still running... :)
OK, so it is the time to open new project on .Net Framework 4.0
In next posts I will cover new .Net 4 features with code samples.