C #: How can I elegantly and easily simplify end-to-end calls?

I have a tcp server which, when a client connects, creates a new stream and adds it to it, but every time I try to access the connection information or something like that, say, even counting the number of clients connected, I I get an illegal cross-thread exception or something like that.

ive read a few guides about things called delegates that challenge and reflect, but all the examples or tutorials just confuse me as one call invokes a specific path in another.

Is there an elegant or simplified way to do this? Do I need to learn to do something else first? or am I just making things more complicated than they are? Any suggestions, links or tips are most appreciated and accepted.

+3
source share
4 answers

I assume you are getting this cross-thread exception as you are trying to update screen elements from your code stream. If you need to do this, you can get a simple solution using an anonymous method.

Suppose you want to add an item to a ListBoxLog. This code will do the trick from any thread:

ListBoxLog.Invoke((MethodInvoker)delegate { ListBoxLog.Items.Add("Done"); });

There is also a property to check .InvokeRequired, you can check if the call is called. Usually you check this property in a function that can be called both by the main user interface thread and by any background thread.

BeginInvoke, Invoke. BeginInvoke .

0

, . . MVP . , " " - , .

, UI, SynchronizationContext , , UI, . . .

+1

Source: https://habr.com/ru/post/1704321/