Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SocketIoClientDotNet Socket.Emit is not thread safe #25

Open
tamasmonus-cas opened this issue May 19, 2016 · 0 comments
Open

SocketIoClientDotNet Socket.Emit is not thread safe #25

tamasmonus-cas opened this issue May 19, 2016 · 0 comments

Comments

@tamasmonus-cas
Copy link

I'm using the SocketIoClientDotNet in a WPF (.NET 4.5) application. I'm calling the Emit method in an async function, and it's interchanging the callbacks indeterminently.

I forked the repository and looked after the problem, it's in the Emit method, where the Ids variable is incremented. It is not threadsafe, thus two packets could have the same Id.

I solved this problem with this simple modification:
`public Emitter Emit(string eventString, IAck ack, params object[] args)
{
var log = LogManager.GetLogger(Global.CallerName());

    var _args = new List<object> { eventString };
    if (args != null)
    {
        _args.AddRange(args);                
    }

    var jarray = new JArray(_args);
    var packet = new Packet(Parser.Parser.EVENT, jarray);

    packet.Id = Interlocked.Increment(ref Ids);

    log.Info(string.Format("emitting packet with ack id {0}", packet.Id));
    Acks = Acks.Add(packet.Id, ack);

    Packet(packet);

    return this;

}`

The key part is:
packet.Id = Interlocked.Increment(ref Ids);

It is a thread safe way to increment a variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant