0

I want processing data in a thread and, at the same time, maintaining the control on the UI. In my program, when i click on a "Connect" button, client is connected to a server through a socket, but at the same time i would to start a thread that continuously waits for a message from the server. My code is approxymately:

Thread ListenThread;
SocketClient socket = new SocketClient();

        public MainWindow()
        {
            ListenThread = new Thread(Wait);
            InitializeComponent();
            socket.StartClient(PORT);
        }

private void CONNECT_Click(object sender, RoutedEventArgs e)
        {
            socket.Connect();
            UpdateUI();
            ListenThread.Start();
        }

private void Wait (){
            while (socket.isConnected())
                socket.WaitForSomething();
        }

private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            HandlePressure(e.Key);
        }

The problem is that, when I start ListenThread, I can't use UI (I have a textbox that collects commands that I must send to the server). How I can handle this situation? Thanks.

2 Answers 2

2

You can use Thread.
Remember that if you want call method or any controls of window you must use

Dispatcher.Invoke(new Action(()=>
{
//Call method or controls of window here
}));
Sign up to request clarification or add additional context in comments.

3 Comments

I already use the class Thread. The function Wait doesn't control directly UI and I can't use UI.
Sorry, Could you show me the all code of this file?
now it works, I don't know where was the mistake. Thanks a lot.
0

You should collect all information that you need for ListenThread before you call it and then pass it to ListenThread.Start(param1, param2...) or ListenThread.Start(objectWithParameters).

Doing this way you get data on UI thread, which has access to all UI controls and not from another thread that doesn't have access to UI thread.

When you done with calculation on worker thread (ListenThread) you can update UI controls, by Dispatcher.Invoke method. Calling Dispatcher delegates call to UI thread, where you can have full access to all controls.

1 Comment

In the function called by ListenThread (Wait) I need informations that I already have (socket in this case). I'm not sure understanding what you say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.