Question

Je suis en train de frayer un fil pour prendre soin de la tâche DoWork qui devrait prendre moins de 3 secondes. A l'intérieur DoWork sa prise de 15 secondes. Je veux annuler DoWork et transférer le dos de contrôle à thread principal. J'ai copié le code comme suit et son ne fonctionne pas. Au lieu d'annuler DoWork, il finit toujours DoWork puis transfère le dos de contrôle à thread principal. Qu'est-ce que je fais mal?

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

    private static System.Threading.ManualResetEvent[] resetEvents;

    [STAThread]
    static void Main(string[] args)
    {
        resetEvents = new ManualResetEvent[1];

        int i = 0;

        resetEvents[i] = new ManualResetEvent(false);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork),(object)i);


        Thread.CurrentThread.Name = "main thread";

        Console.WriteLine("[{0}] waiting in the main method", Thread.CurrentThread.Name);

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


        //abort dowork method if it takes more than 3 seconds
        //and transfer control to the main thread.
        do
        {
            if (span.Seconds < 3)
                WaitHandle.WaitAll(resetEvents);
            else
                resetEvents[0].Set();


            end = DateTime.Now;
            span = end.Subtract(start);
        }while (span.Seconds < 2);



        Console.WriteLine(span.Seconds);


        Console.WriteLine("[{0}] all done in the main method",Thread.CurrentThread.Name);

        Console.ReadLine();
    }

    static void DoWork(object o)
    {
        int index = (int)o;

        Thread.CurrentThread.Name = "do work thread";

        //simulate heavy duty work.
        Thread.Sleep(15000);

        //work is done..
        resetEvents[index].Set();

        Console.WriteLine("[{0}] do work finished",Thread.CurrentThread.Name);
    }
}
Était-ce utile?

La solution

fils mis en commun sont des fils de fond, ce qui signifie qu'ils se terminent automatiquement lorsque le le fil de premier plan de l'application (s) fin.

J'ai changé votre boucle et enlevé les resetEvents.

     //abort dowork method if it takes more than 3 seconds 
     //and transfer control to the main thread. 
     bool keepwaiting = true;
     while (keepwaiting)
     {
        if (span.Seconds > 3)
        {
           keepwaiting = false;
        }

        end = DateTime.Now;
        span = end.Subtract(start);
     }

Autres conseils

[STAThread] est Single Thread Apartment. Essayez [MTAThread] qui est multi fil Appartement.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top