How to use parallel tasks that need access to the same ressource.

c#chris

Member
Joined
Dec 10, 2024
Messages
8
Programming Experience
1-3
Hello,

when I try to make my code more effective (faster) via parallel tasks I get Exceptions.
If I remove the parallel tasks everything works as it should.
What I am doing wrong and how can I make my code faster without exceptions.



Here is the code sample:
public class LineManager : INotifyPropertyValueChanged
{

    //.......

    internal List<MyLine> HorizontalLine { get; } = new();

    //.......

    internal void RenderLines(IChart argichart, RenderContext argcontext)
    {
            List<MyLine>? _tempList = null;
            lock (HorizontalLine) _tempList = new(HorizontalLine);
                    foreach (var line in _tempList)
                    {
                        DrawLines(argichart, argcontext, line, line.LineColor, line.LineType);
                    }
    }

    internal void AddLine(MyLine argline)
    {
                lock (HorizontalLine) HorizontalLine.Add(argline);
    }

    //.......
}


internal class MyClass()
{
    public LineManager _lineManager { get; set; } = new();

    private void AddLines()
    {
        _lineManager.AddLine(SupportLine);
    }

    public MyClass() {}

    //Not sure what triggers this but it is used to update GUI
    protected override void OnRender(RenderContext context, DrawingLayouts layout)
    {
        Parallel.Invoke(
                       () => _lineManager.RenderLines(ChartInfo!, context),
                        //and more ...
                    );
    }

    //Called when new data is available
    protected override void OnCalculate(int bar, decimal value)
    {
        Parallel.Invoke(
                       () => AddLines(),
                        //and more ...
                    );
    }
}
 
Last edited by a moderator:
What was the exception you were getting?
 
Last edited:
Hello, see here:

Time Source Message
04.01.2025 18:49:56 Lines.LineManager "DrawLines System.ArgumentException: Destination array was not long enough. Check the destination index, length, and the array's lower bounds. (Parameter 'destinationArray')
at System.Array.CopyImpl(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length)
at System.Collections.Generic.Queue`1.SetCapacity(Int32 capacity)
 
Well, that call stack seems to indicate updating a Queue, rather than adding to a List. So it's what ever that is holding that Queue that needs to do some resource locking, or swap to a queue implementation that is thread safe.
 
Do you make significant gains if you parallelize out to multiple threads, all but one of which must then wait for a shared resource, while only one thread works on it?
 
Back
Top Bottom