I am working on C # with threads but I can not print them in a txt because the error occurs:
The process can not access the file 'C: \ Users \ wuesi \ Desktop \ Data.txt' because it is being used in another process System.IO.IOException
namespace threads
{
class Program
{
static void Main(string[] args)
{
productor hilo_Obj1 = new productor();
productor hilo_Obj2 = new productor();
productor hilo_Obj3 = new productor();
Consumidor hilo_obj4 = new Consumidor();
Receprto hilo_obj5 = new Receprto();
Thread hilo_Uno = new Thread(new ThreadStart(hilo_Obj1.run));
Thread hilo_Dos = new Thread(new ThreadStart(hilo_Obj2.run));
Thread hilo_Tres = new Thread(new ThreadStart(hilo_Obj3.run));
Thread hilo_Cuatro = new Thread(new ThreadStart(hilo_obj4.run_C));
Thread hilo_Cinco = new Thread(new ThreadStart(hilo_obj5.Run_R));
hilo_Uno.Start();
hilo_Dos.Start();
hilo_Tres.Start();
hilo_Cuatro.Start();
hilo_Cinco.Start();
Console.ReadLine();
}
}
class productor : Consumidor
{
int M,i;
public double dataqueue_a, dataqueue_i, dataqueue_c;
public productor()
{
M = 5;
i = 0;
dataqueue_a = 0;
dataqueue_c = 0;
dataqueue_i = 0;
}
public void run()
{
do
{
Random aleatorio_C = new Random();//genero datos entre 97 y 122 para despues imprimirlos con el valor de ascii y generar datos char
int a;
for (i = 0; i < M; i++)
{
a = aleatorio_C.Next(97, 122);
dataqueue_a = a;
if (dataqueue_a != 0)
{
dataqueue.Enqueue(dataqueue_a);
}
}
Random aleatorio_I = new Random();
int b;
for (i = 0; i < M; i++)
{
b = aleatorio_I.Next(1, 50);
dataqueue_i = b;
if (dataqueue_i != 0)
{
dataqueue.Enqueue(dataqueue_i);
}
}
Random aleatorio_F = new Random();
double c;
for (i = 0; i < M; i++)
{
c = aleatorio_F.NextDouble();
dataqueue_c = c;
if (dataqueue_c != 0)
{
dataqueue.Enqueue(dataqueue_c);
}
}
} while (dataqueue.Count == 45);
semaforo = "Done";
run_C();
}
}
class Consumidor:Receprto
{
public String semaforo;
public Queue dataqueue = new Queue();
public void run_C()
{
while (dataqueue.Count > 0)
{
if (sem == true)
{
sem = false;
str = (double)dataqueue.Dequeue();
Run_R();
sem = true;
}
}
}
}
}
class Receprto
{
public double str;
public bool sem=true;
StreamWriter sw = new StreamWriter("C:\Users\wuesi\Desktop\Datos.txt");
public async void Run_R()
{
if (str != null)
{
Console.WriteLine(str);
sw.Write(str);
}
sw.Close();
}
}