commit 79881a53dafd8f6c6f6e68cf708a46600f973e80 Author: juanjo Date: Fri Oct 27 12:14:51 2023 +0200 código psp-csharp-02-hilos diff --git a/01-HelloThreads/01-HelloThreads.csproj b/01-HelloThreads/01-HelloThreads.csproj new file mode 100644 index 0000000..7b2867b --- /dev/null +++ b/01-HelloThreads/01-HelloThreads.csproj @@ -0,0 +1,83 @@ + + + + + Debug + AnyCPU + {B53D1830-2591-46C0-B93D-9A095CE459D1} + WinExe + _01_HelloThreads + 01-HelloThreads + v4.7.2 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/01-HelloThreads/App.config b/01-HelloThreads/App.config new file mode 100644 index 0000000..56efbc7 --- /dev/null +++ b/01-HelloThreads/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/01-HelloThreads/Form1.Designer.cs b/01-HelloThreads/Form1.Designer.cs new file mode 100644 index 0000000..522c54e --- /dev/null +++ b/01-HelloThreads/Form1.Designer.cs @@ -0,0 +1,149 @@ + +namespace _01_HelloThreads { + partial class Form1 { + /// + /// Variable del diseñador necesaria. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Limpiar los recursos que se estén usando. + /// + /// true si los recursos administrados se deben desechar; false en caso contrario. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Código generado por el Diseñador de Windows Forms + + /// + /// Método necesario para admitir el Diseñador. No se puede modificar + /// el contenido de este método con el editor de código. + /// + private void InitializeComponent() { + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.button3 = new System.Windows.Forms.Button(); + this.button4 = new System.Windows.Forms.Button(); + this.button5 = new System.Windows.Forms.Button(); + this.button6 = new System.Windows.Forms.Button(); + this.button7 = new System.Windows.Forms.Button(); + this.button8 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(24, 26); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(99, 43); + this.button1.TabIndex = 0; + this.button1.Text = "Hello Thread"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.Button1_Click); + // + // button2 + // + this.button2.Location = new System.Drawing.Point(152, 26); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(99, 43); + this.button2.TabIndex = 1; + this.button2.Text = "Paralelismo"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.Button2_Click); + // + // button3 + // + this.button3.Location = new System.Drawing.Point(284, 26); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(99, 43); + this.button3.TabIndex = 2; + this.button3.Text = "Variables"; + this.button3.UseVisualStyleBackColor = true; + this.button3.Click += new System.EventHandler(this.Button3_Click); + // + // button4 + // + this.button4.Location = new System.Drawing.Point(407, 26); + this.button4.Name = "button4"; + this.button4.Size = new System.Drawing.Size(99, 43); + this.button4.TabIndex = 3; + this.button4.Text = "Paso Parámetros"; + this.button4.UseVisualStyleBackColor = true; + this.button4.Click += new System.EventHandler(this.Button4_Click); + // + // button5 + // + this.button5.Location = new System.Drawing.Point(523, 26); + this.button5.Name = "button5"; + this.button5.Size = new System.Drawing.Size(99, 43); + this.button5.TabIndex = 4; + this.button5.Text = "Nombrar Hilos"; + this.button5.UseVisualStyleBackColor = true; + this.button5.Click += new System.EventHandler(this.Button5_Click); + // + // button6 + // + this.button6.Location = new System.Drawing.Point(639, 26); + this.button6.Name = "button6"; + this.button6.Size = new System.Drawing.Size(99, 43); + this.button6.TabIndex = 5; + this.button6.Text = "Propiedades"; + this.button6.UseVisualStyleBackColor = true; + this.button6.Click += new System.EventHandler(this.Button6_Click); + // + // button7 + // + this.button7.Location = new System.Drawing.Point(335, 92); + this.button7.Name = "button7"; + this.button7.Size = new System.Drawing.Size(99, 43); + this.button7.TabIndex = 6; + this.button7.Text = "Fore/Background"; + this.button7.UseVisualStyleBackColor = true; + this.button7.Click += new System.EventHandler(this.Button7_Click); + // + // button8 + // + this.button8.Location = new System.Drawing.Point(216, 92); + this.button8.Name = "button8"; + this.button8.Size = new System.Drawing.Size(99, 43); + this.button8.TabIndex = 7; + this.button8.Text = "Listar Threads en Proceso"; + this.button8.UseVisualStyleBackColor = true; + this.button8.Click += new System.EventHandler(this.button8_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.button8); + this.Controls.Add(this.button7); + this.Controls.Add(this.button6); + this.Controls.Add(this.button5); + this.Controls.Add(this.button4); + this.Controls.Add(this.button3); + this.Controls.Add(this.button2); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + + } + + #endregion + + + private System.Windows.Forms.Button button7; + private System.Windows.Forms.Button button6; + private System.Windows.Forms.Button button5; + private System.Windows.Forms.Button button4; + private System.Windows.Forms.Button button3; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button button8; + } +} + diff --git a/01-HelloThreads/Form1.cs b/01-HelloThreads/Form1.cs new file mode 100644 index 0000000..99ed136 --- /dev/null +++ b/01-HelloThreads/Form1.cs @@ -0,0 +1,130 @@ +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); + } + } + } +} diff --git a/01-HelloThreads/Form1.resx b/01-HelloThreads/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/01-HelloThreads/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/01-HelloThreads/Program.cs b/01-HelloThreads/Program.cs new file mode 100644 index 0000000..9e75b3c --- /dev/null +++ b/01-HelloThreads/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace _01_HelloThreads { + static class Program { + /// + /// Punto de entrada principal para la aplicación. + /// + [STAThread] + static void Main() { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/01-HelloThreads/Properties/AssemblyInfo.cs b/01-HelloThreads/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e205ca0 --- /dev/null +++ b/01-HelloThreads/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// La información general de un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie estos valores de atributo para modificar la información +// asociada con un ensamblado. +[assembly: AssemblyTitle("01-HelloThreads")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("01-HelloThreads")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles +// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde +// COM, establezca el atributo ComVisible en true en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. +[assembly: Guid("b53d1830-2591-46c0-b93d-9a095ce459d1")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de compilación +// Revisión +// +// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión +// utilizando el carácter "*", como se muestra a continuación: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/01-HelloThreads/Properties/Resources.Designer.cs b/01-HelloThreads/Properties/Resources.Designer.cs new file mode 100644 index 0000000..d4f4c7c --- /dev/null +++ b/01-HelloThreads/Properties/Resources.Designer.cs @@ -0,0 +1,66 @@ +//------------------------------------------------------------------------------ +// +// Este código fue generado por una herramienta. +// Versión de runtime: 4.0.30319.42000 +// +// Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si +// el código se vuelve a generar. +// +//------------------------------------------------------------------------------ + + +namespace _01_HelloThreads.Properties { + /// + /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. + /// + // StronglyTypedResourceBuilder generó automáticamente esta clase + // a través de una herramienta como ResGen o Visual Studio. + // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen + // con la opción /str o recompile su proyecto de VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_01_HelloThreads.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las + /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/01-HelloThreads/Properties/Resources.resx b/01-HelloThreads/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/01-HelloThreads/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/01-HelloThreads/Properties/Settings.Designer.cs b/01-HelloThreads/Properties/Settings.Designer.cs new file mode 100644 index 0000000..f3e0ff0 --- /dev/null +++ b/01-HelloThreads/Properties/Settings.Designer.cs @@ -0,0 +1,27 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace _01_HelloThreads.Properties { + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/01-HelloThreads/Properties/Settings.settings b/01-HelloThreads/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/01-HelloThreads/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/02-ThreadSincro/02-ThreadSincro.csproj b/02-ThreadSincro/02-ThreadSincro.csproj new file mode 100644 index 0000000..4fe42c8 --- /dev/null +++ b/02-ThreadSincro/02-ThreadSincro.csproj @@ -0,0 +1,83 @@ + + + + + Debug + AnyCPU + {36162286-86B2-49C9-981F-BEE67CBDCB8A} + WinExe + _03_ThreadSincro + 03-ThreadSincro + v4.7.2 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/02-ThreadSincro/App.config b/02-ThreadSincro/App.config new file mode 100644 index 0000000..56efbc7 --- /dev/null +++ b/02-ThreadSincro/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/02-ThreadSincro/Form1.Designer.cs b/02-ThreadSincro/Form1.Designer.cs new file mode 100644 index 0000000..4c91aa1 --- /dev/null +++ b/02-ThreadSincro/Form1.Designer.cs @@ -0,0 +1,134 @@ +namespace _02_ThreadSincro +{ + partial class Form1 + { + /// + /// Variable del diseñador necesaria. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Limpiar los recursos que se estén usando. + /// + /// true si los recursos administrados se deben desechar; false en caso contrario. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Código generado por el Diseñador de Windows Forms + + /// + /// Método necesario para admitir el Diseñador. No se puede modificar + /// el contenido de este método con el editor de código. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.button3 = new System.Windows.Forms.Button(); + this.button4 = new System.Windows.Forms.Button(); + this.button5 = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(26, 24); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(111, 39); + this.button1.TabIndex = 0; + this.button1.Text = "Rellena Array"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.Button1_Click); + // + // button2 + // + this.button2.Location = new System.Drawing.Point(26, 82); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(111, 39); + this.button2.TabIndex = 1; + this.button2.Text = "Monitor"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.Button2_Click); + // + // button3 + // + this.button3.Location = new System.Drawing.Point(26, 145); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(111, 39); + this.button3.TabIndex = 2; + this.button3.Text = "Ping Pong"; + this.button3.UseVisualStyleBackColor = true; + this.button3.Click += new System.EventHandler(this.Button3_Click); + // + // button4 + // + this.button4.Location = new System.Drawing.Point(26, 199); + this.button4.Name = "button4"; + this.button4.Size = new System.Drawing.Size(111, 39); + this.button4.TabIndex = 3; + this.button4.Text = "Abortar"; + this.button4.UseVisualStyleBackColor = true; + this.button4.Click += new System.EventHandler(this.Button4_Click); + // + // button5 + // + this.button5.Location = new System.Drawing.Point(26, 255); + this.button5.Name = "button5"; + this.button5.Size = new System.Drawing.Size(111, 46); + this.button5.TabIndex = 4; + this.button5.Text = "Interactuar Formulario"; + this.button5.UseVisualStyleBackColor = true; + this.button5.Click += new System.EventHandler(this.Button5_Click); + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(154, 255); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(126, 20); + this.textBox1.TabIndex = 5; + // + // textBox2 + // + this.textBox2.Location = new System.Drawing.Point(154, 281); + this.textBox2.Name = "textBox2"; + this.textBox2.Size = new System.Drawing.Size(126, 20); + this.textBox2.TabIndex = 6; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.button5); + this.Controls.Add(this.button4); + this.Controls.Add(this.button3); + this.Controls.Add(this.button2); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button3; + private System.Windows.Forms.Button button4; + private System.Windows.Forms.Button button5; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.TextBox textBox2; + } +} + diff --git a/02-ThreadSincro/Form1.cs b/02-ThreadSincro/Form1.cs new file mode 100644 index 0000000..811b496 --- /dev/null +++ b/02-ThreadSincro/Form1.cs @@ -0,0 +1,185 @@ +using System; +using System.Diagnostics; +using System.Threading; +using System.Windows.Forms; + +namespace _02_ThreadSincro { + public partial class Form1 : Form { + public Form1() { + InitializeComponent(); + } + + private int[] numeros = new int[1000]; + int iterador; + int numero; + private void Button1_Click(object sender, EventArgs e) { + iterador = 0; + numero = 0; + //crear + Thread t1 = new Thread(this.rellena); + Thread t2 = new Thread(this.rellena); + Thread t3 = new Thread(this.rellena); + Thread t4 = new Thread(this.rellena); + Thread t5 = new Thread(this.rellena); + + //inicializar + t1.Start(); + t2.Start(); + t3.Start(); + t4.Start(); + t5.Start(); + + //esperar + t1.Join(); + t2.Join(); + t3.Join(); + t4.Join(); + t5.Join(); + + //ver resultado + for (int i = 0; i < 1000; i++) { + Debug.WriteLine(numeros[i]); + } + } + Object o = new object(); + private void rellena() { + for (int i = 0; i < 200; i++) { + lock (o) { + numero++; + numeros[iterador] = numero; + Thread.Sleep(50); + iterador++; + } + } + } + + private void Button2_Click(object sender, EventArgs e) { + Thread t1 = new Thread(this.rellenaM); + Thread t2 = new Thread(this.leeM); + t1.Start(); + t2.Start(); + } + + static bool fin_bloqueo = false; + //método asociado al hilo productor + private void rellenaM() { + for (int i = 999; i >= 0; i--) { + numeros[i] = i; + //Thread.Sleep(5); + } + lock (this) { + fin_bloqueo = true; + Monitor.Pulse(this); + } + } + + //método asociado al hilo consumidor + private void leeM() { + Thread.Sleep(500); + lock (this) + while (!fin_bloqueo) + Monitor.Wait(this); + for (int i = 0; i < 1000; i++) { + Debug.WriteLine(numeros[i]); + } + } + + private void Button3_Click(object sender, EventArgs e) { + Thread t1 = new Thread(this.Ping); + Thread t2 = new Thread(this.Pong); + t1.Start(); + t2.Start(); + } + + object o1 = new object(); + object o2 = new object(); + + private void Ping() { + for (int i = 0; i < 1000; i++) { + lock (o2) + Monitor.Pulse(o2); + lock (o1) { + Monitor.Wait(o1); + Debug.WriteLine("ping"); + } + } + } + + private void Pong() { + for (int i = 0; i < 1000; i++) { + lock (o1) + Monitor.Pulse(o1); + lock (o2) { + Monitor.Wait(o2); + Debug.WriteLine("PONG"); + } + } + } + + private void Button4_Click(object sender, EventArgs e) { + //creo + Thread t1 = new Thread(this.LongFor); + + t1.Start(); + Thread.Sleep(100); + Debug.WriteLine("Abortando thread t1"); + if (t1.IsAlive) Debug.WriteLine("Hilo t1 vivo antes de abort"); + t1.Abort(); + if (t1.IsAlive) Debug.WriteLine("Hilo t1 vivo después de abort"); + t1.Join(); + Debug.WriteLine("Fin de prueba"); + } + + private void LongFor() { + try { + for (int i = 0; i < 1000; i++) { + Debug.WriteLine(">>>Thread trabajando"); + Thread.Sleep(100); + } + } + catch (ThreadAbortException e) { + Debug.WriteLine(">>>Excepción capturada: "+ e.Message); + Thread.ResetAbort(); + } + Debug.WriteLine(">>>Thread todavía vivo"); + Thread.Sleep(1000); + Debug.WriteLine(">>>Thread finalizando"); + } + + + private void Button5_Click(object sender, EventArgs e) { + //de esta forma no funcionaría + //Thread t1 = new Thread(this.EscribeText1); + //t1.Start(); + + Thread t1 = new Thread(this.EscribeText2); + t1.Start(); + + } + + private void EscribeText1() { + this.textBox1.Text = "Hola"; + } + + delegate void DelegadoText(); + + delegate void DelegadoTextParametros(string s); + + private void EscribeText2() { + //invocación delegado sin parámetros + DelegadoText dc1 = new DelegadoText(this.Escribir); + this.Invoke(dc1); + + //invocación a un delgado con parámetros + DelegadoTextParametros dc2 = new DelegadoTextParametros(this.Escribir2); + this.Invoke(dc2, "hola con parámetros"); + } + + private void Escribir() { + this.textBox1.Text = "TEXTO"; + } + private void Escribir2(string s) { + this.textBox2.Text = s; + } + } +} diff --git a/02-ThreadSincro/Form1.resx b/02-ThreadSincro/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/02-ThreadSincro/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/02-ThreadSincro/Program.cs b/02-ThreadSincro/Program.cs new file mode 100644 index 0000000..1c6e65a --- /dev/null +++ b/02-ThreadSincro/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace _02_ThreadSincro +{ + static class Program + { + /// + /// Punto de entrada principal para la aplicación. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/02-ThreadSincro/Properties/AssemblyInfo.cs b/02-ThreadSincro/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3d74f0c --- /dev/null +++ b/02-ThreadSincro/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// La información general de un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie estos valores de atributo para modificar la información +// asociada con un ensamblado. +[assembly: AssemblyTitle("03-ThreadSincro")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("03-ThreadSincro")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles +// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde +// COM, establezca el atributo ComVisible en true en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. +[assembly: Guid("36162286-86b2-49c9-981f-bee67cbdcb8a")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de compilación +// Revisión +// +// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión +// utilizando el carácter "*", como se muestra a continuación: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/02-ThreadSincro/Properties/Resources.Designer.cs b/02-ThreadSincro/Properties/Resources.Designer.cs new file mode 100644 index 0000000..34b5dff --- /dev/null +++ b/02-ThreadSincro/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// Este código fue generado por una herramienta. +// Versión de runtime: 4.0.30319.42000 +// +// Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si +// el código se vuelve a generar. +// +//------------------------------------------------------------------------------ + +namespace _02_ThreadSincro.Properties +{ + + + /// + /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. + /// + // StronglyTypedResourceBuilder generó automáticamente esta clase + // a través de una herramienta como ResGen o Visual Studio. + // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen + // con la opción /str o recompile su proyecto de VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_02_ThreadSincro.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las + /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/02-ThreadSincro/Properties/Resources.resx b/02-ThreadSincro/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/02-ThreadSincro/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/02-ThreadSincro/Properties/Settings.Designer.cs b/02-ThreadSincro/Properties/Settings.Designer.cs new file mode 100644 index 0000000..144310b --- /dev/null +++ b/02-ThreadSincro/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace _02_ThreadSincro.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/02-ThreadSincro/Properties/Settings.settings b/02-ThreadSincro/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/02-ThreadSincro/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Threads.sln b/Threads.sln new file mode 100644 index 0000000..0892ff5 --- /dev/null +++ b/Threads.sln @@ -0,0 +1,35 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28729.10 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01-HelloThreads", "01-HelloThreads\01-HelloThreads.csproj", "{B53D1830-2591-46C0-B93D-9A095CE459D1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02-ThreadSincro", "02-ThreadSincro\02-ThreadSincro.csproj", "{36162286-86B2-49C9-981F-BEE67CBDCB8A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D1DC89DE-204A-4571-AD00-B53A161006E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1DC89DE-204A-4571-AD00-B53A161006E2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1DC89DE-204A-4571-AD00-B53A161006E2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1DC89DE-204A-4571-AD00-B53A161006E2}.Release|Any CPU.Build.0 = Release|Any CPU + {B53D1830-2591-46C0-B93D-9A095CE459D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B53D1830-2591-46C0-B93D-9A095CE459D1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B53D1830-2591-46C0-B93D-9A095CE459D1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B53D1830-2591-46C0-B93D-9A095CE459D1}.Release|Any CPU.Build.0 = Release|Any CPU + {36162286-86B2-49C9-981F-BEE67CBDCB8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {36162286-86B2-49C9-981F-BEE67CBDCB8A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {36162286-86B2-49C9-981F-BEE67CBDCB8A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {36162286-86B2-49C9-981F-BEE67CBDCB8A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {E899D1C0-BA4E-4621-B82C-CC913F352B2E} + EndGlobalSection +EndGlobal