Thursday, April 11, 2013

threading 101

Chapter 21 of C# 4.0 in a Nutshell is on Threading. I spun up the corny example below and I can tell that it is writing to two files at once as is desired. If I were to use try/catches to make sure a different note was logged when a thread failed (which would be smart) I would do it inside the Foo and Bar methods and not inside the Go method for if you wrap the newing up of threads in a try the catch will never be reached. The failure will go unseen in such a circumstance.

using System;
using System.IO;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MvcApplication.Tests
{
   [TestClass]
   public class UnitTest
   {
      [TestMethod]
      public void Go()
      {
         Thread foo = new Thread(Foo);
         Thread bar = new Thread(Bar);
         foo.Start();
         bar.Start();
         foo.Join();
         bar.Join();
         Assert.AreNotEqual("Blondie", "Deborah Harry");
      }
      
      static void Foo()
      {
         for (int i = 0; i < 10000; i++)
         {
            using (StreamWriter baz =
                  File.AppendText(@"C:\Users\Thomas\Desktop\baz.txt"))
            {
               baz.WriteLine("(baz" + DateTime.Now + ")");
            }
         }
      }
      
      static void Bar()
      {
         for (int j = 0; j < 10000; j++)
         {
            using (StreamWriter qux =
                  File.AppendText(@"C:\Users\Thomas\Desktop\qux.txt"))
            {
               qux.WriteLine("(qux" + DateTime.Now + ")");
            }
         }
      }
   }
}

No comments:

Post a Comment