0

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) { }
    }
}
Daniel
  • 9,491
  • 12
  • 50
  • 66
Mennan
  • 4,451
  • 13
  • 54
  • 86
  • You don't need to use async/await - in fact, you can't use async/await with .Net 4, so the question is moot. – Matthew Watson Dec 23 '16 at 12:56
  • i know that async/await can be used in .net 4.0 in some way, but question is really do i need actually i dont know – Mennan Dec 23 '16 at 12:59
  • Yeah, you don't *need* to use it; it's just a way to simplify async programming. I assume that the `Thread.Sleep(1000 * 4);` is just a way of emulating some code that can't be cancelled for a few seconds. – Matthew Watson Dec 23 '16 at 13:15

1 Answers1

1

Do you really need to use the async/await keywords to be able to start and stop a task? No.

Should you use the async/await keywords in your web service? Not necessarily because you don't really seem to benefit much from being able to capture the context and execute the remainder of the method once a task has finisihed. Your Start method just fires off 3 tasks and return without waiting for any of the tasks to finish. So this method isn't really "awaitable" or asynchronous by nature.

You could have made use of the async/await keywords in your Stop method if you wanted to make it asynchronous, i.e. you wanted any caller of this method be able to call it asynchronously and do something once the tasks have actually been stopped:

public async Task StopAsync()
{
    tokenSource.Cancel();
    await Task.WhenAll(Tasks.ToArray());
    Console.WriteLine("all finished");
    Start();
}


await StopAsync();
//now all tasks have been stopped...do something

When using the async and await keywords the compiler basically generates a state machine for you. The beginning of an async method is executed just like any other method and when it hits an "await" keyword it returns from the method and tells the awaitable (that is the asynchronous operation) to run the remainder of the method once it has completed. Please refer to the following link for more information about this.

How and When to use `async` and `await`

Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88