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:

  1. task.run runs asynchronously in threadpool, keeps main thread free time.
  2. lock(_lock) ensures 1 thread writing stream @ single moment, (threads spawned threadpool task.run)
  3. you don't need separate writecallback, use inline lambda callback methods. makes life easier.

let me know if solves problem.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -