Skip to content

ReadAsync Causing OPC Server Thread Leak #75

@qwas368

Description

@qwas368

Below is the test code I used. As you can see, this is an infinite loop continuously reading data through ReadAsync.

for (; ;)
{
    Logger logger = new Logger(nameof(OpcController), nameof(GetItemValues));
    using var server = new OpcDaServer(_opcClientConfigSection.ProgId);
    server.Connect();
    using OpcDaGroup group = server.AddGroup(Guid.NewGuid().ToString("N"));
    OpcDaItemDefinition[] definitions = items
        .Select(x => new OpcDaItemDefinition
        {
            ItemId = x,
            IsActive = true
        })
        .ToArray();
    OpcDaItemResult[] results = group.AddItems(definitions);
    OpcDaItemValue[] values = await group.ReadAsync(group.Items);
}

However, after running it, you can see through Task Manager that the Process Threads of the OPC Server keep increasing.
image

Then I found that changing await group.ReadAsync(group.Items) to group.ReadAsync(group.Items).Result can avoid the issue, but obviously, this is not the root cause. So I tried to find the real cause in the source code

private readonly TaskCompletionSource<OpcDaItemValue[]> _tcs = new TaskCompletionSource<OpcDaItemValue[]>();

and discovered that adding TaskCreationOptions.RunContinuationsAsynchronously to the following code can solve the problem.

private readonly TaskCompletionSource<OpcDaItemValue[]> _tcs = new TaskCompletionSource<OpcDaItemValue[]>(TaskCreationOptions.RunContinuationsAsynchronously);

Honestly, I am not familiar with Async and don't understand the underlying principle. I hope someone can help explain.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions