c# - Mutex Across Threads? -
so, getting exception code below. have put exception details it, believe caused fact different thread releases lock 1 starts lock. want potentially allow main thread continue while writes queue , occur.
first , foremost, want know if there way can done? secondly, should done or bad plan? have looked @ manualresetevent, monitor , mutex of seem this. note, network server , first time writing multithreaded, potentially high traffic one.
exception: thrown first time send (and callback) called.
system.applicationexception on mutex.releasemutex(). "object synchronization method called unsynchronized block of code."
public void sendasync(byte[] packet) { mutex.waitone(); client.getstream().beginwrite(packet, 0, packet.length, writecallback, null); } private void writecallback(iasyncresult ar) { client.getstream().endwrite(ar); mutex.releasemutex(); console.writeline("sent data " + remoteendpoint); }
considering -
i want potentially allow main thread continue while writes queue , occur.
first , foremost, want know if there way can done?
i don't think need mutex that. looking -
static object _lock = new object(); //somewhere based on context public void sendasync(byte[] packet) { task.run(() => { ..... other codes lock (_lock) { client.getstream().beginwrite(packet, 0, packet.length, ar => // write callback (lambda) { client.getstream().endwrite(ar); console.writeline("sent data " + remoteendpoint); }, null); } }); } explanation:
task.runruns asynchronously in threadpool, keeps main thread free time.lock(_lock)ensures 1 thread writing stream @ single moment, (threads spawnedthreadpooltask.run)- you don't need separate
writecallback, use inlinelambda callbackmethods. makes life easier.
let me know if solves problem.
Comments
Post a Comment