VansFannel VansFannel - 18 days ago 6
C# Question

Run a new thread immediately

I'm developing a WPF app with C# and .NET Framework 4.6.1 and SQL Server 2012 SP3 and Entity Framework 6.1.3 Code First.

I need to run a thread immediately but now it doesn't run immediately with this code:

Task.Run(() =>
{
RequestNewCodes();
});
private void RequestNewCodes()
{
log.DebugFormat("Task thread ID: {0} - {1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow.ToString("hh:mm:ss.fff"));

try
{
trazabilidad.InsertNewCodesWeb(1, codesManagerURL);
}
catch (Exception ex)
{
log.Error(string.Format("InsertNewCodesWeb nivel 1: {0}", ex.ToString()));
}
}


Task.Run
documentation said:


Queues the specified work to run on the thread pool and returns a Task
object that represents that work.


But I don't want to queue it.

How can I run a thread immediately without using ThreadPool?

Immediately means not to push the task in a pool and wait its turn.

I'm not reusing connections. Every time I connect to database I create a new DbContext and destroy it at the end.

This is not a duplicate question. I have tested all the answer for that question and it doesn't work for me. I have found how to solve this problem and I want to share with you but I can't because this question is closed.

Answer

The simplest way is to just instantiate a Thread

Thread task = new Thread(()=>
{
     try
     {
         ConnectToCodeManager();

         string connectionString = ConfigurationManager.ConnectionStrings["DataBaseConnection"].ConnectionString;

         SQLTrazabilidadStorage storage = new SQLTrazabilidadStorage(connectionString);

         storage.SendAggregation(parentCode, codesManagerURL);
     }
     catch (Exception ex)
     {
         log.Error(string.Format("SendAggregation to TrzCodesManagerWS: {0}", ex.ToString()));
     }
});
task.Start();