0

I have a StreamSocket in UWP and I send my messages like this using a DataWriter object using the StoreAsync() method:

        public static async Task<bool> SendNetworkMessage(NetworkMember member, NetworkMessage message)
    {
        DataWriter writer = member.DataWriter;

        //Check that writer is not null
        if (writer != null)
        {
            try
            {
                //Serialize Message
                string stringToSend = SerializeObject<NetworkMessage>(message);

                //Send Message Length
                writer.WriteUInt32(writer.MeasureString(stringToSend));

                //Send Message
                writer.WriteString(stringToSend);

                await writer.StoreAsync();


                return true;
            }
            catch (Exception e)
            {

                Debug.WriteLine("DataWriter failed because of " + e.Message);

                Debug.WriteLine("");

                Disconnect(member);

                OnMemberDisconnectedEvent(member);
                return false;
            }
        }
        else { return false; }
    }

All is well, the only problem is that I don't know if a connection went down. Now I want to check my connection using a DispatcherTimer like this:

        private static async void NetworkTimer_Tick(object sender, object e)
    {
        foreach (NetworkMember member in networkMemberCollection)
        {
            if (member.Connected == true && member.Disconnecting == false)
            {
                await SendNetworkMessage(member, new PingMessage());

            }
        }}

However, this is causing timing issues which is causing ObjectDisposedExceptions on the DataWriter. It seems that the DispatcherTimer thread cannot use the StreamSocket when I send a message from a different thread. My question is: How can I make sure the Ping is sent each time but that SendNetworkMessage operations are done in order instead of overlapping?

Thanks

WJM
  • 1,137
  • 1
  • 15
  • 30

1 Answers1

0

It seems that the DispatcherTimer thread cannot use the StreamSocket when I send a message from a different thread.

How can I make sure the Ping is sent each time but that SendNetworkMessage operations are done in order instead of overlapping?

It's possible, and I think your code using foreach and await operation can ensure the work of sending message in order.

the only problem is that I don't know if a connection went down.

If you want to know if the connection went down, you can refer to Handling WinRT StreamSocket disconnects (both server and client side).

Community
  • 1
  • 1
Grace Feng
  • 16,564
  • 2
  • 22
  • 45