The background threads concept in .NET framework is so much confusing, and sometimes irrelevant to what you might actually be doing.
If I had to write this sort of application in today's version, I would choose async/await sort of programming, instead of the delegates way, because,
1. Delegates are tough to understand and properly program.
2. Delegates have other things to be handled as well; callbacks etc.
3. .NET has async/await, that are meant to replace the asynchronous programming with delegates and begin/end functions.
However, the concept of async/await will be simpler in this case. Because of the fact, that you will leave majority of the asynchronous programming to the framework itself. Also, .NET framework has several
Async
functions that return
Task
objects. We can use them and program our apps asynchronously. Something like this,
public MainForm() {
startServer();
}
private void startServer() {
server = new TcpListener();
while(true) {
listen();
}
}
private async void listen() {
var client = await server.AcceptTcpClientAsync();
label.Text = "Client Connected";
}
The reason I am suggesting async/await instead of delegates is the simplicity and other features;
less resources are consumed in async/await because there is just one thread doing all unless you specify to use more.
Oh, right, you can also modify this to work with the Socket class, I feel TCP specific class to be more simpler and handier. :-)
TcpListener Class (System.Net.Sockets)[
^]
One more thing, you do not need to handle the Dispatcher or invocation here, because in the async/await code, only one thread is accessing resources, thus no need to load the UI update code back to the dispatcher pump.
Update
I can think of multiple ways of sending and updating the text on the main form, two of them are,
1) Create a static label field in the form, and set that to the label which you want to update, then use that field from the server class.
public class MainForm {
public static Label MyLabel { get; set; }
public MainForm() {
MyLabel = this.label1;
}
}
public void listen() {
MainForm.MyLabel.Text = "Updated text";
}
public void updateLabel (string message) {
MainForm.MyLabel.Text = message;
}
2) The other way is to pass a reference of your current MainForm, to the server class so that server can use that object and update its values. This is somewhat ambiguous approach so I will not recommend, but just so that you know,
public class Server {
public static MainFrom parentForm { get; set; }
public Server(MainForm referenceForm) {
parentForm = referenceForm;
}
public void updateField(string message) {
parentForm.label1.Text = message;
}
}
And of course, you can have other ways as well. They all work quite similar, you need to pass the reference and then through that reference.