سؤال

I am writing an application where i have to use multiple threads, each of these threads will preform a task and at the end of that task will update a progress bar to indicate the overall progress. The problem is that because i cant control these threads they could potentially clash, i have used locking as a preventative measure but i have also been advised to use the following code, or some variation of it. I would like your opinion as to where this code should be placed.

var temp = updateProcess; //updateProcess is the event getting fired
        if (temp != null)
        {
            var eventListeners = temp.GetInvocationList();
            foreach (EventHandler e in eventListeners)
            {
                e.BeginInvoke(this, null, EndAsyncImageAcquiredEvent, null);
            }
        }
        else
        {
            throw new FatalException("No handler is attached to the camera's ImageAcquiredEvent");
        }

should i create a separate method that each thread calls, and that method then uses this code to fire each event update or should this code be included in the spun out method that each thread executes.

Thanks in advance for any help

هل كانت مفيدة؟

المحلول

What is the shared resource you are trying to obtain that might cause the clash? If it is the progress bar, than it can only be updated through the UI thread itself, all you need to do is use Invoke and InvokeRequired from your threads. see: Using InvokeRequired vs control.InvokeRequired

If you have any other shared resources, When using the lock , if done correct (no deadlocks etc...) the code will be thread safe, but that will come at a performance cost.

Finally, I would use tasks instead of threads see: How to update UI from child tasks in WinForms

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top