Home C# Never Ending Task
Post
Cancel

C# Never Ending Task

무한루프(While문) 쓰기 싫을 때

NeverEndingTask.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public abstract class NeverEndingTask
{
    private CancellationTokenSource? wtoken;
    private ITargetBlock<DateTimeOffset>? _task;

    public abstract Task DoAsync(CancellationToken cancellationToken);

    ITargetBlock<DateTimeOffset> CreateNeverEndingTask(
       Func<DateTimeOffset, CancellationToken, Task> action,
       CancellationToken cancellationToken)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));

        ActionBlock<DateTimeOffset>? block = null;
        block = new ActionBlock<DateTimeOffset>(async now =>
        {
            await action(now, cancellationToken).ConfigureAwait(false);
            //await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false);

            block?.Post(DateTimeOffset.Now);
        }, new ExecutionDataflowBlockOptions
        {
            CancellationToken = cancellationToken
        });

        return block;
    }

    public void StartNeverEndingTask()
    {
        try
        {
            wtoken = new CancellationTokenSource();

            _task = CreateNeverEndingTask((now, ct) => DoAsync(ct), wtoken.Token);
            _task.Post(DateTimeOffset.Now);
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"{ex}");
        }

    }

    public void StopNeverEndingTask()
    {
        using (wtoken)
        {
            wtoken?.Cancel();
        }
        wtoken?.Dispose();
        wtoken = null;
        _task = null;
    }
}

ConcreteNeverEndingTask.cs

1
2
3
4
5
6
7
8
9
public class ConcreteNeverEndingTask : NeverEndingTask
{
    public override async Task DoAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("DO ASYNC TASK");

        await Task.Delay(TimeSpan.FromMilliseconds(1000), cancellationToken).ConfigureAwait(false);
    }
}

main.cs

1
2
3
ConcreteNeverEndingTask neverEndingTask = new();
neverEndingTask.StartNeverEndingTask();
neverEndingTask.StopNeverEndingTask();
This post is licensed under CC BY 4.0 by the author.