Reputation: 461
I'm trying to do my first multithread-windows form app and i have 1 important problem. I know that i have to use Invoke or BeginInvoke in my thread to change RichTextBox in my form, but my UI just freezing when i'm trying to do it,while console is printing correctly my results.
class MyThread
{
public MyThread()
{
}
public void Run()
{
byte[] tmp;
while (true)
{
// lock (sem1)
Monitor.Enter(sem1);
{
if (end)
{
Monitor.Exit(sem1);
break;
}
tmp = inp.ReadNr();
if (inp.End())
end = true;
}
if(inOrder)
Monitor.Enter(sem2);
Monitor.Exit(sem1);
bool p = CSL.checkNr((byte[])tmp.Clone());
Monitor.Enter(sem3);
if(inOrder)
Monitor.Exit(sem2);
{
outp.WriteNr(tmp, p);
//win.richTextBox2.AppendText(String.Join("", tmp) + '\n');
win.richTextBox2.BeginInvoke(new Action(delegate ()
{
win.richTextBox2.AppendText("wtf");
}));
}
Monitor.Exit(sem3);
}
}
}
"win" is object of my class Form1. I can't deal with it...
EDIT:
static public void loading()
{
outp = new oFile();
Thread[] thr = new Thread[nrThreads];
for (int a = 0; a < nrThreads; a++)
new Thread(new ThreadStart(new MyThread().Run)).Start();
//new MyThread().Run();
Console.ReadKey();
}
Form:
private void button1_Click(object sender, EventArgs e)
{
Program.loading();
}
Upvotes: 1
Views: 616
Reputation: 391276
The problem here is this line in Program.loading
:
Console.ReadKey();
This stops the main GUI thread in its track, so let's see what happens now:
So remove that line of code and at least your program should not stop dead in its tracks like before.
Having said that, I urge you to try simpler examples to begin with. Your interleaved, manual, handling of multiple monitors leaves me thinking you're at the very start of learning about multithreaded programming, and have started with some complex gears that need to interlock quite accurately to work correctly.
Instead I would ask you to look at async / await
, new keywords added in C# 5 to handle asynchronous programming. Though asynchrony and multithreading is not the same thing, nor does either imply the other, asynchronous programming usually gets you most of the way towards a responsive UI that won't freeze while waiting for things.
Upvotes: 3