0

I have a Dictionary that is Dictionary<int, RSendPacket> _Packets and there are two main threads. Thread #1 adding packets with this function

public void EnqueueOutgoingData(int id, byte[] data)
{
    RSendPacket packet = new RSendPacket(data);
    _Packets.Add(id, packet);
}

The Thread #2 is reads and sends the packet via socket like this

private void _Process(RSendPacket packet)
{
    foreach (KeyValuePair<int, RSendPacket> o in _Packets)
    {
        //Socket send (o.Value >> That's RSendPacket class)
    }
}

at this point, I'm getting an error. I'm adding "asdf" but it carries it as "► o". It is a threading/memory error I think but I cant fix it because I don't know how! Can anybody help me about this? (I can implement a system in C++ with pointers and memory management and it should be a memory management problem -caused by my bad c#)

EDIT1: And yes there isn't a thread-safe implemention but I've tried it with 'lock()' and not works!

EDIT2: Oh another important edit. I'm using C# 2.0 with Unity. So solution should be a C# 2.0 (mono) code :/

PilawyerDev
  • 271
  • 2
  • 16
  • Where do you see the "corrupted" value? In the `_Process` method? If you only queue and process a single packet does that work? (I'm thinking this would rule out multi-threading issues in determining the cause of the corruption.) – richaux Feb 15 '14 at 15:43
  • Also, at what point do you remove the sent packet from the `_Packets` collection? ... and is the `packet` passed in to `_Process` of any significance? – richaux Feb 15 '14 at 15:47

4 Answers4

0

Looks like you might want to use a queue for this kind of operation, it fits better what you are trying to do.

If you experience concurrency issues, you can use the ConcurrentQueue class.

Andrea
  • 884
  • 1
  • 10
  • 23
  • 1
    It must be a dictionary because I need to find my values with a id key. – PilawyerDev Feb 15 '14 at 15:32
  • 1
    In your example you are iterating through the keyValuePairs and sending the value only - please update your code with relevant details about how you are using the dictionary to get better advice! – Andrea Feb 15 '14 at 15:35
0

You don't have to use a lock to keep it thread safe. simply use ConcurrentDictionary in place of the regular dictionary.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
0

A Dictionary<TKey, TValue> is not thread-safe, so behavior is undefined in your multi-threaded example. Also, the order in which items are returned when iterating over a Dictionary<TKey, TValue> is undefined, so you might not get what you expect even if you use a ConcurrentDictionary<TKey, TValue> or implement your own locking.

Joe
  • 122,218
  • 32
  • 205
  • 338
0

The real solution (I've tried and that works) is l3arnon's answer but I'm going to implement this system in C# 2.0 and I've implemented it like this method with Monitor.

Community
  • 1
  • 1
PilawyerDev
  • 271
  • 2
  • 16