I want to make server application. In the beginning it should make thread for organizing every connection and write logs in Listbox. I have problem because i don’t know where can i make new thread which would have access to Form1.Listbox1. This is what i tried:
public class ServerLoop
{
Form1 form1;
public ServerLoop(Form1 f)
{
form1 = f;
}
public void loop()
{
form1.addConsoleMessage("test");
}
}
And Form1 class:
public partial class Form1 : Form
{
public Thread tServerLoop;
public ServerLoop serverLoop;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
console.Items.Clear();
players.Items.Clear();
players.Items.Add("Witaj w serwerze");
addConsoleMessage("test");
serverLoop = new ServerLoop(this);
tServerLoop = new Thread(serverLoop.loop);
tServerLoop.Start();
}
private void connectButton_Click(object sender, EventArgs e)
{
}
public void addConsoleMessage(String msg)
{
console.Items.Add(msg);
}
}
Anyone knows what can i do to acheive this?
Well, you could use
Invoketo marshal a delegate back onto the UI thread where thatListBoxcan be safely accessed.But alas, this option is inferior. Actually, these marshaling techniques are generally terrible. Do not get me wrong. There is a time and place for
Invoke(and the like), but this, like many situations, is not one of them.Invokecalls all over the place.BeginInvoke).Invokeanyway).So how would I solve this problem? Well, with the boring old
System.Windows.Forms.Timerand the fancy newConcurrentQueue<T>of course.So what do we have now.
This solution is not completely devoid of disadvantages though. Now that we have our worker thread speeding along it is possible that it produces more items for the queue then what the UI thread can consume. It would not typically be a problem, but there are techniques for dealing with that.