using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; using System.Diagnostics; namespace _01_HelloThreads { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Button1_Click(object sender, EventArgs e) { Thread t = new Thread(this.Hola); t.Start(); this.Hola(); } private void Hola() { Debug.WriteLine("Hola"); } private void Button2_Click(object sender, EventArgs e) { Thread t = new Thread(this.EscribeY); t.Start(); for (int i = 0; i < 1000; i++) { Debug.Write("X"); } } private void EscribeY() { for (int i = 0; i < 1000; i++) { Debug.Write("y"); } } bool Done; private void Button3_Click(object sender, EventArgs e) { this.Done = false; Thread t = new Thread(this.TareaUno); t.Start(); this.TareaUno(); } private void TareaUno() { if (!Done) { Debug.WriteLine("Tarea realizada"); //Thread.Sleep(500); this.Done = true; } } private void Button4_Click(object sender, EventArgs e) { //primera forma de pasar parámetros con expresión lambda Thread t1 = new Thread(() => this.Mensaje("Lara")); t1.Start(); //segunda forma de pasar parámetros Thread t2 = new Thread(this.Mensaje2); t2.Start("Selene"); this.Mensaje("María"); } private void Mensaje(string nombre) { Debug.WriteLine("Hola " + nombre); } private void Mensaje2(object nombre) { String n = (string)nombre; Debug.WriteLine("Hola " + n); } private void Button5_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Thread t = new Thread(this.Identificador); t.Name = "hilo" +i; t.Start(); } Thread.CurrentThread.Name = "PRINCIPAL"; this.Identificador(); } private void Identificador() { Debug.WriteLine("Hola desde: " + Thread.CurrentThread.Name + ", mi identificador es: " +Thread.CurrentThread.ManagedThreadId); } private void Button6_Click(object sender, EventArgs e) { Thread.CurrentThread.Priority = ThreadPriority.Highest; Thread t = new Thread(this.EscribeY); t.Priority = ThreadPriority.Lowest; t.Start(); for (int i = 0; i < 1000; i++) { Debug.Write("X"); } } private void Button7_Click(object sender, EventArgs e) { Thread t = new Thread(this.LongGo); t.IsBackground = true; t.Start(); } private void LongGo() { for (int i = 0; i < 1000; i++) { Thread.Sleep(500); Debug.Write("y"); } } private void button8_Click(object sender, EventArgs e) { Process.GetCurrentProcess().Refresh(); ProcessThreadCollection pc = Process.GetCurrentProcess().Threads; Debug.WriteLine("Procesos totales: " + pc.Count); foreach (ProcessThread t in pc) { Debug.WriteLine("Identificador: "+ t.Id + ", estado: " + t.ThreadState); } } } }