NetworkStream.Read() from 2 threads?

costin tudor 6 Reputation points
2020-12-28T19:31:08.5+00:00

so i am making a chatting program and stuff, and the user can create his own group to chat in with people, now, here is the thing, i have a different thread that listens any data from the server.

but the thing is, i am worried because if the server sends data to the client, the thread might as well read it, possibly bugging/crashing the client.

so is there a way to like pause the listen thread?

also the client and server communicates using json data, so if i like send a type from the server, it might throw an exception, because the thread listener uses a different class than the create group one.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,356 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,576 Reputation points
    2020-12-29T06:52:12.097+00:00

    The chat room is where the client sends information to the server, and then the server broadcasts the information to all clients. Therefore, if you stop monitoring the information in the server, the entire chat room may be suspended.

    I have not developed such a commercial project, so I don't know the most correct way to solve this situation.

    My idea is to send a message with a specific identifier in the server-side code, and then detect it in the client code, the identification is used to determine whether the original source of this information is other clients or the server itself.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. costin tudor 6 Reputation points
    2020-12-29T09:56:25.043+00:00

    Also i forgot to say that, status infos like group creation success aren't send as json. (they don't even have to).
    they are sent like "GROUPCREATE_SUCCESS" or stuff like that. i have already found out the answer to my problem: simply use the try catch, so that if it is not valid json, it assigns a variable to it, the variable is then read by the create group button method.

    1 person found this answer helpful.