i m new in task jobs and need to help. I have a web service,
this service will stop all tasks and start again in every 30 mins.
Q1= Is that regular code sample ?
Q2= This code works for me, but do i need ASYNC AWAIT in this project ? i'm using .net 4.0.
Thx.
private CancellationTokenSource tokenSource;
private List<Task> Tasks;
public virtual void Start()
{
// start
Tasks = new List<Task>();
tokenSource = new CancellationTokenSource();
for (int i = 0; i < 3; i++)
{
Tasks.Add(Task.Factory.StartNew(() => SomeWork(),
tokenSource.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default));
}
}
public void Stop()
{
tokenSource.Cancel();
Task.Factory.ContinueWhenAll(Tasks.ToArray(), t =>
{
Console.WriteLine("all finished");
// start again
Start();
});
}
int i = 0;
public void SomeWork()
{
while (!tokenSource.IsCancellationRequested)
{
try
{
Thread.Sleep(1000 * 4);
Console.WriteLine(Task.CurrentId + " finised!");
}
catch (Exception) { }
}
}