Posts

Showing posts from October, 2016

C# Updated on Threading with .net 4

With .NET 4 we now have better ways of handling threads. So in this post I'm going to demonstrate several ways of creating and waiting for threads to finish. First example is creating 10 threads with the new Task.Factory.StartNew() method then we call Task.WaitAll and the framework handles the rest. This call will however block until all the tasks are finished. // Wait for all tasks to complete. Task[] tasks = new Task[10]; for (int i = 0; i < 10; i++) { tasks[i] = Task.Factory.StartNew(() => DoSomeWork(10000000)); } Task.WaitAll(tasks); The second way allows us to no block. var task1 = DoWorkAsync(); var task2 = DoMoreWorkAsync(); await Task.WhenAll(task1, task2);

C# parse invalid XML characters

I've been dealing with XML a bit lately and have found that when you don't control the data you get all sorts of weird stuff. XML 1.0 doesn't allow certain characters or the XML is invalid. I tested a variety of ways using streams and string builders but I found a bit of LINQ and using a .NET function and in two lines you get a string of XML that only has valid characters. var validXmlChars = val.Where( ch => XmlConvert.IsXmlChar( ch ) ).ToArray(); return new string( validXmlChars );