vs2002: c# multi threading question..

Posted by dotnet-practitioner on Stack Overflow See other posts from Stack Overflow or by dotnet-practitioner
Published on 2010-06-03T16:50:00Z Indexed on 2010/06/03 16:54 UTC
Read the original article Hit count: 153

Filed under:
|

I would like to invoke heavy duty method dowork on a separate thread and kill it if its taking longer than 3 seconds. Is there any problem with the following code?

class Class1
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    /// 

    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("starting new thread");

        Thread t = new Thread(new ThreadStart(dowork));
        t.Start();

        DateTime start = DateTime.Now;
        TimeSpan span = DateTime.Now.Subtract(start);

        bool wait = true;
        while (wait == true)
        {
            if (span.Seconds>3)
            {
                t.Abort();
                wait = false;
            }
            span = DateTime.Now.Subtract(start);
        }

        Console.WriteLine("ending new thread after seconds = {0}", span.Seconds);
        Console.WriteLine("all done");
        Console.ReadLine();

    }

    static void dowork()
    {

        Console.WriteLine("doing heavy work inside hello");
        Thread.Sleep(7000);
        Console.WriteLine("*** finished**** doing heavy work inside hello");
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading