From 42aa484126b71d9303b79d97b348dc7c496dd258 Mon Sep 17 00:00:00 2001 From: Giang Nguyen Date: Mon, 1 Jan 2024 21:52:11 +0200 Subject: [PATCH] refactor: Fixed `PackageService.SavePlcLibraryAsync` The use of ThreadLocal with `AutomationInterface` is not good. --- src/TwinGet.Core/Packaging/PackageService.cs | 8 +++----- src/TwinGet.TwincatInterface/TwincatProject.cs | 4 ++-- test/Test.Utils.Test/TestTwincatProjectTests.cs | 2 +- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/TwinGet.Core/Packaging/PackageService.cs b/src/TwinGet.Core/Packaging/PackageService.cs index 580e7f4..ccc54e5 100644 --- a/src/TwinGet.Core/Packaging/PackageService.cs +++ b/src/TwinGet.Core/Packaging/PackageService.cs @@ -168,13 +168,11 @@ private static async Task SavePlcLibraryAsync(IPackCommand packCommand) StaTaskScheduler staTaskScheduler = new(1); - using var ai = new ThreadLocal(() => new AutomationInterface()); - // Begin AutomationInterface. var initAiTask = Task.Factory.StartNew( () => { - var _ = ai.Value; // We do this so that ThreadLocal inititalize AutomationInterface(); + return new AutomationInterface(); }, CancellationToken.None, TaskCreationOptions.None, @@ -195,7 +193,7 @@ private static async Task SavePlcLibraryAsync(IPackCommand packCommand) var savePlcLibTask = initAiTask.ContinueWith( (prevTask) => { - prevTask.Wait(); + using AutomationInterface ai = prevTask.Result; lock (libraryPathLock) { @@ -204,7 +202,7 @@ private static async Task SavePlcLibraryAsync(IPackCommand packCommand) // Suppress because we are in try block. #pragma warning disable CS8602 // Dereference of a possibly null reference. libraryPath = - ai.Value.SavePlcProject( + ai.SavePlcProject( packCommand.Path, packCommand.OutputDirectory, resolvedSolution diff --git a/src/TwinGet.TwincatInterface/TwincatProject.cs b/src/TwinGet.TwincatInterface/TwincatProject.cs index bc03948..3486e7a 100644 --- a/src/TwinGet.TwincatInterface/TwincatProject.cs +++ b/src/TwinGet.TwincatInterface/TwincatProject.cs @@ -42,12 +42,12 @@ public TwincatProject(EnvDTE.Project project) _plcProjects = new(TryGetPlcProjects(_systemManager, _project.FullName)); } - private static IReadOnlyList TryGetPlcProjects( + private static List TryGetPlcProjects( ITcSysManagerAlias systemManager, string filePath ) { - List plcProjects = new(); + List plcProjects = []; ArgumentException.ThrowIfNullOrEmpty(filePath, nameof(filePath)); diff --git a/test/Test.Utils.Test/TestTwincatProjectTests.cs b/test/Test.Utils.Test/TestTwincatProjectTests.cs index 04331fb..6fba8f6 100644 --- a/test/Test.Utils.Test/TestTwincatProjectTests.cs +++ b/test/Test.Utils.Test/TestTwincatProjectTests.cs @@ -1,7 +1,7 @@ // This file is licensed to you under MIT license. using FluentAssertions; -namespace Test.Utils; +namespace Test.Utils.Test; public class TestTwincatProjectTests {