Sunday, June 28, 2009

C# BackgroundWorker

From time to time, we all create GUIs for our applications. One of the most annoying things about a GUI is when it locks up, or gives the appearance of locking up. The quickest solution for this problem is Application.DoEvents().

That's fine for something that is looping quickly, but there is a better solution. It's easy to fix this problem with the C# BackgroundWorker Class. What it does is create another thread for you to do long running tasks on that would slow down your GUI.

In Visual Studio, create a new C# Windows Forms project. On the form, select from the Toolbox, under the Components Section, the BackgroundWorker object and drop it on the form. In the grey area below the form, you will see backgroundWorker1. Double click it to create the DoWork() method. This is where you will put your long running task.

Now, when you need to update, or touch, any UI component like a ProgressBar or TextBox, you cannot do that from a BackgroudWorker thread. Let's say we need to append a line of text to a textbox from our background thread. Let's create a method to do this:


private void AppendTextToDebugWindow(string textToAppend)
        {
            textBox1.AppendText(textToAppend + Environment.NewLine);
        }
Now, if you call this from your backgroundworker, you will get an InvalidOperationException - Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.

This is pretty easy to fix. Create a delegate with the same signature as the above method. In our case:
delegate void AppendTextToDebugWindowHandler(string textToAppend);
Then, in the AppendTextToDebugWindow, change it to look like this:

private void AppendTextToDebugWindow(string textToAppend)
        {
            if (textBox1.InvokeRequired)
            {
                this.Invoke(new AppendTextToDebugWindowHandler(this.AppendTextToDebugWindow), new object[] { textToAppend });
                return;
            }
            textBox1.AppendText(textToAppend + Environment.NewLine);
        }
See! I told you this was easy! Here's is the sample Form1 that I used:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace TestBackgroundWorker
{
    delegate void AppendTextToDebugWindowHandler(string textToAppend);

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Don't forget to check if the background worker is busy
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
                return;
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            AppendTextToDebugWindow("backgroundWorker1 started");
            Thread.Sleep(5000);
            AppendTextToDebugWindow("backgroundWorker1 done");
        }

        private void AppendTextToDebugWindow(string textToAppend)
        {
            if (textBox1.InvokeRequired)
            {
                this.Invoke(new AppendTextToDebugWindowHandler(this.AppendTextToDebugWindow), new object[] { textToAppend });
                return;
            }
            textBox1.AppendText(textToAppend + Environment.NewLine);
        }
    }
}

Thursday, June 18, 2009

C#: How to setup and use TransactionScope

Many of us developers have used SqlTransaction to ensure data integrity. But, SqlTransaction works on only one database. You can get it to work across multiple databases buy using the Save() method, but it gets ugly. There is a much better solution, TransactionScope. TransactionScope uses DTC (aka MSDTC) to manage the Sql Transactions and promoting transactions from Lightweight Transaction Manager (LTM) to full DTC.

Let’s see what we need to do to get SqlTransaction to work across multiple databases:


public void DoWorkSqlTransactions()
{
using (SqlConnection con1 = new SqlConnection("my connection string"))
using (SqlConnection con2 = new SqlConnection("my second connection string"))
{
try
{
con1.Open();
con2.Open();
SqlTransaction tran1 = con1.BeginTransaction();
SqlTransaction tran2 = con2.BeginTransaction();

try
{
SqlCommand cmd1 = new SqlCommand("update ...", con1, tran1);
cmd1.ExecuteNonQuery();

// Don't want select in transaction
cmd1 = new SqlCommand("select ...", con1);

SqlCommand cmd2 = new SqlCommand("insert ...", con2, tran2);
cmd2.ExecuteNonQuery();
tran1.Save("savepoint");
tran2.Save("savepoint");
tran1.Commit();
tran2.Commit();
}
catch (Exception)
{
tran1.Rollback();
tran2.Rollback();
}
}
catch (Exception)
{
// error handling for connection failure
}
finally
{
con1.Close();
con2.Close();
}
}
}

Now, try to do that with 5 or more databases at the same time! And try passing those SqlTransaction objects around! Really, really ugly code. Let’s look at the same code, but with TransactionScope:


public void DoWorkSqlTransactionScope()
{
try
{
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
using (SqlConnection con1 = new SqlConnection("my connection string"))
using (SqlConnection con2 = new SqlConnection("my second connection string"))
{
con1.Open();
con2.Open();

SqlCommand cmd1 = new SqlCommand("update ...", con1);
cmd1.ExecuteNonQuery();

// Suppress the select statement from the transaction:
using (TransactionScope ts2 = new TransactionScope(TransactionScopeOption.Suppress))
{
cmd1 = new SqlCommand("select ...", con1);
cmd1.ExecuteReader(); // and so on...
}

SqlCommand cmd2 = new SqlCommand("insert ...", con2);
cmd2.ExecuteNonQuery();

ts.Complete();
}
}
catch (Exception)
{
// whole transaction was rolled back automatically
}
}
As you can see, any call to the db made within the TransactionScope is automatically enrolled in a transaction. This is true even if the call is made in another class, or external dll! Think of what that can do for you…. If you don’t want to include something, suppress it like I did in the above example.

To use TransactionScope, you need to configure the machine you are developing on and the machine the application will be deployed on for DTC.

Configuring DTC is pretty simple to get working, and a little more work to secure. Follow this guide to configure it for Vista and Server 2008: http://technet.microsoft.com/en-us/library/cc753510(WS.10).aspx

For most other Windows Operating Systems, the short of it is run dcomcnfg for Component Services. Expand Component Services, Computers. Right click My Computer in the left pane, select Properties. Open the MSDTC tab. Select Security Configuration button. Check all the check boxes and select the “No Authentication Required” radio button. It may suggest to restart the DTC service, which is fine, do it. DTC may need to be configured on your Sql Server, too.

Now that the OS is configured for DTC, now we have to setup our project. Just add a reference for System.Transactions to the project, and a using clause for System.Transactions to the file where the class wrapping all the sql calls is, even if it is the ui or business layer. At the end of the using clause, call Complete() on the TransactionScope variable to commit the all the transactions.

Wednesday, June 17, 2009

C#: Simple Threading Example Using ThreadPool

With machines now being sold with multiple cores, why should your application be using only one? Harness the full potential of the processor(s) and make your app shine!

Threading seems so complicated, it really isn’t. Today, I’ll provide an example of the simplest thread code you’ve ever seen. In fact, it’s so simple, here it is:

class TheTest
{
public void Go()
{
for (int i = 0; i < 100; i++)
{
WaitCallback wcb = new WaitCallback(this.DoWork);
ThreadPool.QueueUserWorkItem(wcb, i);
}
Console.ReadLine();
}

public void DoWork(object state)
{
int i = (int)state;
Console.WriteLine(string.Format("{0:d3} started",i));
Thread.Sleep(500);
Console.WriteLine(string.Format("{0:d3} done", i));
}
}

Create a new instance of the TheTest class, call go. You’ll see 100 threads get created and do work. You can pass in anything you want for the state. That’s a very good place to put your “unit of work” that the thread must work on. Just make sure you add a using clause for System.Threading.

Of course, this post doesn’t touch on any locking or blocking issues, I’ll do that later. But for now, why not multithread?