Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use a custom defined lock to a string value?
    text
    copied!<p>I am unsure whether to use Mutex or Semaphore or some other facility.</p> <p>Here is my scenario: In a multithreaded environment some event results into an image being written to disk. This image is generated in the event handler.</p> <p>The issue is, that the event A causes an image A.png being written and event B an image called B.png.</p> <p>If those events occur at the same time the images can be saved (although obviously the disk does not handle parallel writes very well) but it is a valid scenario.</p> <p>But there are times when event A is fired multiple times. This is also valid but calling image.Save for the same file name leads to a Generic GDI error.</p> <p>How can I lock the .Save(...) call with a facility without locking every thread (like using the lock keyword)</p> <p>I thought about a handmade solution where the handler writes the filename into a lookup table and then writes the file. Other handlers would need to check the lookup and then do some Thread.Sleep or similar. But this does look like the naive approach to resource locking.</p> <p>Is there a proper way for such custom locks that do lock around a "virtual" resource? (Virtual as it may not exist at the time of locking).</p> <p><strong>Update and edit:</strong> The image generation performs some number crunching and is therefore wrapped in a Task. A typical scenario would be always creating multiple images at the same time to utilize the Thread.Pool. I know that a job queue would solve the issue but it would remove the parallel execution. If I would distribute the jobs to n-threads manually (which would mean writing my own pool, right?) I would still run into the problem that two threads could try to write the same file.</p> <p>The event source is unreliable, therefore it might call the write operation multiple times with the same file but actually as long as one "image A" generation is either in work or not yet started the second, third or whatever event handling can be ignored.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload