I have simple program where i am calling my main function Start() from timer after every 10 minutes.
i have seen that my main function is getting hit but suddenly finish before executing whole function code.i am confused and not able to understand why this is happening. please guide me what i am missing in my code.
class Program
{
public static bool IsRunning =false;
static void Main(string[] args)
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(10);
var timer = new System.Threading.Timer((e) =>
{
Run();
}, null, startTimeSpan, periodTimeSpan);
}
static async void Run()
{
if (!IsRunning)
{
IsRunning = true;
ModelCompare oCompare = new ModelCompare();
var task1 = oCompare.Start();
await Task.WhenAll(task1);
IsRunning = false;
}
}
}
public class ModelCompare
{
public async Task<bool> Start()
{
//lots of line here to execute and at the end return true
//return Task.FromResult(true);
return true;
}
}
Thanks
EDIT
Found another good sample code.
using System;
using System.Threading.Tasks;
using System.Threading;
namespace DemoApp
{
internal class Program
{
private static int _isRunning = 0;
private static async Task Main(string[] args)
{
// No program can run infinitely. We have to provide a mechanism for safe termination.
var tcs = new CancellationTokenSource();
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(10);
// This mechanism is CTRL+C, so we catch this.
Console.CancelKeyPress += (sender, e) =>
{
tcs.Cancel();
e.Cancel = true;
};
try
{
await Task.Delay(startTimeSpan, tcs.Token);
// No endless loop. We are checking for a cancellation request!
while (!tcs.IsCancellationRequested)
{
// Perform your work.
var task1 = Run(tcs.Token);
var task2 = Task.Delay(periodTimeSpan, tcs.Token);
// If the execution time of Run is greater than periodTimeSpan, we will wait. Depends on your needs.
await Task.WhenAll(task1, task2);
}
}
catch (TaskCanceledException)
{
Console.WriteLine("User canceled your app.");
}
}
private static async Task Run(CancellationToken token)
{
// Should never occur if you use WhenAll()
if (Interlocked.Exchange(ref _isRunning, 1) == 0)
{
ModelCompare oCompare = new ModelCompare();
await oCompare.Start(token);
// More work...
_isRunning = 0;
}
}
}
public class ModelCompare
{
public async Task<bool> Start(CancellationToken token)
{
// Use
// token.ThrowIfCancellationRequested();
// to check at suitable moments if the user wants to abort.
return true;
}
}
}