@@ -13,7 +13,7 @@ public class PyCodeInterpreter : ICodeProcessor
1313 private readonly IServiceProvider _services ;
1414 private readonly ILogger < PyCodeInterpreter > _logger ;
1515 private readonly CodingSettings _settings ;
16- private static SemaphoreSlim _semLock = new ( initialCount : 1 , maxCount : 1 ) ;
16+ private static readonly SemaphoreSlim _semLock = new ( initialCount : 1 , maxCount : 1 ) ;
1717
1818 public PyCodeInterpreter (
1919 IServiceProvider services ,
@@ -31,15 +31,7 @@ public CodeInterpretResponse Run(string codeScript, CodeInterpretOptions? option
3131 {
3232 if ( options ? . UseLock == true )
3333 {
34- try
35- {
36- return InnerRunWithLock ( codeScript , options , cancellationToken ) ;
37- }
38- catch ( Exception ex )
39- {
40- _logger . LogError ( ex , $ "Error when running code script with lock in { Provider } .") ;
41- return new ( ) { ErrorMsg = ex . Message } ;
42- }
34+ return InnerRunWithLock ( codeScript , options , cancellationToken ) ;
4335 }
4436
4537 return InnerRunCode ( codeScript , options , cancellationToken ) ;
@@ -102,20 +94,25 @@ public async Task<CodeGenerationResult> GenerateCodeScriptAsync(string text, Cod
10294 #region Private methods
10395 private CodeInterpretResponse InnerRunWithLock ( string codeScript , CodeInterpretOptions ? options = null , CancellationToken cancellationToken = default )
10496 {
105- _semLock . Wait ( cancellationToken ) ;
97+ var lockAcquired = false ;
10698
10799 try
108100 {
101+ _semLock . Wait ( cancellationToken ) ;
102+ lockAcquired = true ;
109103 return InnerRunCode ( codeScript , options , cancellationToken ) ;
110104 }
111105 catch ( Exception ex )
112106 {
113- _logger . LogError ( ex , $ "Error in { nameof ( InnerRunWithLock ) } ") ;
107+ _logger . LogError ( ex , $ "Error in { nameof ( InnerRunWithLock ) } in { Provider } ") ;
114108 return new ( ) { ErrorMsg = ex . Message } ;
115109 }
116110 finally
117111 {
118- _semLock . Release ( ) ;
112+ if ( lockAcquired )
113+ {
114+ _semLock . Release ( ) ;
115+ }
119116 }
120117 }
121118
0 commit comments