I have a stored procedure to clean up some data.
When I invoke from Program.cs like following its not working
static void Main(string[] args)
{
LogCleaner logCleaner = new LogCleaner(appConfiguration);
Task.Run(() => logCleaner.Start());
}
LogCleaner.Start function as following
try
{
using(UnitOfWork unitOfWork = new UnitOfWork(this.appConfiguration.DefaultConnectionString))
{
var result = unitOfWork.E3DLogs.CleanUpLogs(this.appConfiguration.CleanUpDayCount);
logger.Info("Clean up stored procedure executed, Result: " result.ToString());
}
}
catch (Exception e)
{
logger.Error("Error while cleaning the log messages. Error Message: " e.Message);
}
unitOfWork.E3DLogs.CleanUpLogs as following
public int CleanUpLogs(int dayCount)
{
return _E3DDbcontext.CleanUpLogs(dayCount);
}
_E3DDbcontext.CleanUpLogs function as following
public virtual int CleanUpLogs(Nullable<int> dayCount)
{
var dayCountParameter = dayCount.HasValue ?
new ObjectParameter("dayCount", dayCount) :
new ObjectParameter("dayCount", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("CleanUpLogs", dayCountParameter);
}
When I invoke from Program.cs like following its working
static void Main(string[] args)
{
LogCleaner logCleaner = new LogCleaner(appConfiguration);
logCleaner.Start();
}
CodePudding user response:
A process (exe) exits when the last non-background thread terminates, which for simple applications means: when Main
exits. The thread-pool that services Task.Run
uses background threads, so they don't count in terms of application lifetime.
Running the code directly prevents this. Alternatively, you could do (if relevant):
static Task Main(string[] args)
{
LogCleaner logCleaner = new LogCleaner(appConfiguration);
var logCleaner = Task.Run(() => logCleaner.Start());
// presumably some other code to run here, because if there wasn't:
// you'd just run logCleaner.Start() directly
return logCleaner; // include the log-cleaner in the application lifetime
}