Eyh, programming guys. I am new to this whole threading business.
Why can't I access a control from a different thread?
- and why do I get an error message about this only if I close my streanwriter after ending the threads?
+ Ia there any logical reason that a streamwriter file should be closed before I use the close method on it?
Cannot write to a closed TextWriter pops up as a errorbox
.....
Message "Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on." string appears in the call stack
There is no error message from VS if I remove the close method.
So withtout it, the program runs and the listbox is filled according to plan
but the output file has no info in it after a run in either case
I know I am probably being braindead, but you should be used to that by now
PS:
this.Invoke((MethodInvoker)(() =>
helped with the listbox, but makes no difference on writing to file
.................
namespace TestRE_Ex1
{
public partial class Form1 : Form
{
private static Mutex mutex = new Mutex();
private static string filePath = "output.txt";
private static System.IO.StreamWriter file = new System.IO.StreamWriter(filePath);
public Form1()
{
InitializeComponent();
}
private Thread trd;
private void startThreadsButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Starting", MessageBoxButtons.OK, MessageBoxIcon.Warning);
for (int i = 0; i < 10; i++) {
trd = new Thread(() => threadTask(i+1));
trd.Start();
}
// file.Close();
}
Random rnd;
private void threadTask(int id)
{
mutex.WaitOne();
//listBox1.Items.Add("Starting thread " + (id + 1));
this.Invoke((MethodInvoker)(() => listBox1.Items.Add("Starting thread " + (id + 1))));
this.Invoke((MethodInvoker)(() => listBox1.Refresh()));
rnd = new Random();
int ms = rnd.Next(1000);
string info = "Thread id:" + id + ". Sleep time in ms:" + ms;
Thread.Sleep(ms);
writeToFile(info);
this.Invoke((MethodInvoker)(() => listBox1.Items.Add("Finishing thread " + id + "Sleep time:" + ms )));
this.Invoke((MethodInvoker)(() => listBox1.Refresh()));
mutex.ReleaseMutex(); //*
}
private void writeToFile(string info)
{
file.WriteLine(info);
}
}
}
//
Beginner's Guide to Threading in .NET: Part 3 of n - CodeProject
//
c# - How to add item to listBox from other thread? - Stack Overflow