Why sometimes windows service app can't build dynamic assembly?

Łukasz Gabryel 1 Reputation point
2020-12-07T15:14:09.353+00:00

I have some server app. This app run, read some files, create C# classes, build this and load assembly. This app can work in two modes - one mode is window desktop application, and other mode - as windows service but core in dll is common.

Sometimes when this app work long time as service, and machine server has long timeup, they can't build anything. I attach debugger, and debug service. I debug .NET source (CompileAssemblyFromSource), and I see, that .NET classes just run csc.exe process with some params (CSharpCodeProvider class), but csc.exe run, return no errors or exceptions, output is blank and nothing is happend. No assembly is build.

I wrote some dump test service to compile code:

namespace CompilerService
{
  public class Compiler
  {
    private Task _compilerTask;
    public Compiler()
    {
      _compilerTask = Task.Run(() => CompileHalloWorld());
    }

    private const string _workingDir = @"C:\tmp";

    private void CompileHalloWorld()
    {
      System.Threading.Thread.Sleep((30000));

      if (!Directory.Exists(_workingDir))
      {
        Directory.CreateDirectory(_workingDir);
      }
      Directory.SetCurrentDirectory(_workingDir);

      var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
      var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
      parameters.GenerateExecutable = true;
      CompilerResults results = null;
      try
      {
        results = csc.CompileAssemblyFromSource(parameters,
          @"using System;
            class Program {
              public static void Main(string[] args) {
                Console.WriteLine(""Hallo World!"");
              }
            }");
      }
      catch (Exception e)
      {
        int a = 2;
      }
      results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }

  }
}

This dump service is fail too with build hallo world in this state of machine.

After restart machine, all work again ok, compile and load assembly all the time. After few weeks, problem come back, and we must reset server. This problem is on only one machine. On otger machines this service and csc.exe work perfect from years.

If machine is in this wird state, csc.exe dont build in windows service app, but when We run this app as Windows Desktop App all work fine, and csc.exe build normal...

Can you tell me, this is some known issue, oraz is some solution of don't compile csc.exe without machine restart?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,362 questions
{count} votes