Showing posts from May, 2010

C# Equal vs CompareTo

Out of curiosity I decided to run some speed tests on strings using the Equals and CompareTo methods. I wrote some quick code and came up with some interesting results: This test was run for 10000000 iterations. The Equals methods trounced the CompareTo method. Under the hood Equals stops when the first character that doesn't match is found. CompareTo continues on to the end of the string all the time. However this was a case insensitive search with no culture information. Adding more variables may cloud the water a bit, but that is going to be reserved for future posts. The code used in the test can be seen below. using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Threading; namespace Sandbox { class Program { static void Main( string[] args ) { const int counter = 10000000; int i = 0; int count =

C# using a background worker

This post is going to focus on creating and using a BackgroundWorker object. Background workers are found in the System.ComponentModel namespace. They're pretty easy to use. You just create a new object, assign a few properties and event handlers and let it do its thing. using System; using System.ComponentModel; First let's create a background worked object and set it up. Pstatic void Main( string[] args { // create the background worker object BackgroundWorker _worker = new BackgroundWorker(); // tell the background worker it can be cancelled and report progress _worker.WorkerReportsProgress = true; _worker.WorkerSupportsCancellation = true; // a worker thread object where the actual work happens WorkerThread thread = new WorkerThread(); // add our event handlers _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( thread.RunWorkerCompleted ); _worker.ProgressChanged += new ProgressChangedEventHandler( thread.ProgressCha