thread parameterizedthreadstart paralelos metodos hilos example creacion arreglo c# multithreading

parameterizedthreadstart - C#Llama a un método en un nuevo hilo.



parameterizedthreadstart c# example (5)

¡En .Net Threads está gestionado por Thread Pool para que pueda iniciarlo y olvidarse de él! Considere este código.

new Thread(new ThreadStart(SecondFoo)).Start();

Estoy buscando una manera de llamar a un método en un nuevo hilo (usando C #).

Por ejemplo, me gustaría llamar a SecondFoo() en un nuevo hilo. Sin embargo, me gustaría terminar el hilo cuando termine SecondFoo() .

He visto varios ejemplos de subprocesos en C# , pero ninguno que se aplique a este escenario específico donde necesito que el subproceso generado se termine. es posible?

¿Cómo puedo forzar que el subproceso generado que ejecuta Secondfoo() termine al finalizar?

¿Alguien ha encontrado algún ejemplo de esto?


¿Realmente tiene que ser un hilo, o puede ser una tarea también?

Si es así, la forma más fácil es:

Task.Factory.StartNew(() => SecondFoo())


A menos que tenga una situación especial que requiera un subproceso que no sea de grupo de subprocesos, solo use un subproceso de grupo de subprocesos como este:

Action secondFooAsync = new Action(SecondFoo); secondFooAsync.BeginInvoke(new AsyncCallback(result => { (result.AsyncState as Action).EndInvoke(result); }), secondFooAsync);

Garantías que EndInvoke está llamado a cuidar de la limpieza por usted.


Por lo que yo entiendo, necesitas significar terminar como Thread.Abort() ¿verdad? En este caso, simplemente puede salir de Foo (). O puedes usar Process para atrapar el hilo.

Thread myThread = new Thread(DoWork); myThread.Abort(); myThread.Start();

Ejemplo de proceso:

using System; using System.Diagnostics; using System.ComponentModel; using System.Threading; using Microsoft.VisualBasic; class PrintProcessClass { private Process myProcess = new Process(); private int elapsedTime; private bool eventHandled; // Print a file with any known extension. public void PrintDoc(string fileName) { elapsedTime = 0; eventHandled = false; try { // Start a process to print a file and raise an event when done. myProcess.StartInfo.FileName = fileName; myProcess.StartInfo.Verb = "Print"; myProcess.StartInfo.CreateNoWindow = true; myProcess.EnableRaisingEvents = true; myProcess.Exited += new EventHandler(myProcess_Exited); myProcess.Start(); } catch (Exception ex) { Console.WriteLine("An error occurred trying to print /"{0}/":" + "/n" + ex.Message, fileName); return; } // Wait for Exited event, but not more than 30 seconds. const int SLEEP_AMOUNT = 100; while (!eventHandled) { elapsedTime += SLEEP_AMOUNT; if (elapsedTime > 30000) { break; } Thread.Sleep(SLEEP_AMOUNT); } } // Handle Exited event and display process information. private void myProcess_Exited(object sender, System.EventArgs e) { eventHandled = true; Console.WriteLine("Exit time: {0}/r/n" + "Exit code: {1}/r/nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime); } public static void Main(string[] args) { // Verify that an argument has been entered. if (args.Length <= 0) { Console.WriteLine("Enter a file name."); return; } // Create the process and print the document. PrintProcessClass myPrintProcess = new PrintProcessClass(); myPrintProcess.PrintDoc(args[0]); } }


Si realmente comienzas un nuevo hilo, ese hilo terminará cuando el método finalice:

Thread thread = new Thread(SecondFoo); thread.Start();

Ahora se SecondFoo a SecondFoo en el nuevo hilo, y el hilo terminará cuando se complete.

¿De verdad quiso decir que quería que el hilo terminara cuando el método en el hilo de llamada se completa?

EDITAR: Tenga en cuenta que iniciar un hilo es una operación razonablemente cara. ¿Definitivamente necesitas un hilo completamente nuevo en lugar de usar un hilo de subprocesos? Considere usar ThreadPool.QueueUserWorkItem o (preferiblemente, si está usando .NET 4) TaskFactory.StartNew .