Task with Console(with SemaphoreSlim)

背景:
1.在UI程序中执行task本身无特殊之处,但若要在Console中执行呢?进一步,如果再加上async呢?再进一步,如果想实现循环调用呢?经过思索,一篇拙作应运而生。
技术特点:console+task+async+loop.
方式一:
采用最简单的变量控制方式:

private int RunCount = 0;
public void Show()
{
    RunCount++;

    bool IsPathInput = false; string path = string.Empty; string keyword = string.Empty;
    while (!IsPathInput)
    {
        path = "C:\\工作目录\\工作项目\\js";
        if (!string.IsNullOrEmpty(path))
        {
            IsPathInput = true;
        }
    }
    bool IsKeyInput = false;
    while (!IsKeyInput)
    {
        keyword = "A000079";
        if (!string.IsNullOrEmpty(keyword))
        {
            IsKeyInput = true;
        }
    }
    Stopwatch sw = new Stopwatch();
    sw.Start();

    Task t = Task.Run(async () =>
    {
        await foreach (var number in SearchTask(path, keyword))
        {
            Console.WriteLine(number);
        }
    });
    t.ContinueWith(t =>
    {
        sw.Stop();
        Console.WriteLine($"第{RunCount}次查找,耗时:{sw.Elapsed}秒");
        Console.Write("是否继续:");

        var ps = Console.ReadLine();
        if (string.Compare(ps, "Y", true) == 0)
        {
            result = 1;
        }
        else
        {
            Environment.Exit(0);
        }
    });

    while (result == 0)
    {
    }
    if (result == 1)
    {
        Console.WriteLine($"正在执行第{RunCount + 1}次...");
        result = 0;
        Show();
    }
}

 方式二,使用信号量SemaphoreSlim

private static SemaphoreSlim semaphore  = new SemaphoreSlim(0, 1);
public void ShowWithSemaphore()
{
    RunCount++;
    bool IsPathInput = false; string path = string.Empty; string keyword = string.Empty;
    while (!IsPathInput)
    {
        path = "C:\\工作目录\\js";
        if (!string.IsNullOrEmpty(path))
        {
            IsPathInput = true;
        }
    }
    bool IsKeyInput = false;
    while (!IsKeyInput)
    {
        keyword = "A000079";
        if (!string.IsNullOrEmpty(keyword))
        {
            IsKeyInput = true;
        }
    }
    Stopwatch sw = new Stopwatch();
    sw.Start();

    Task t = Task.Run(async () =>
    {
        await foreach (var number in SearchTask(path, keyword))
        {
            Console.WriteLine(number);
        }
    });
    t.ContinueWith(t =>
    {
        sw.Stop();
        Console.WriteLine($"执行完成第{RunCount}次,耗时:{sw.Elapsed}秒");
        Console.Write("是否继续:");
        var ps = Console.ReadLine();
        if (string.Compare(ps, "Y", true) == 0)
        {
            semaphore.Release();
        }
        else
        {
            semaphore.Release();
            Environment.Exit(0);
        }
    });
    semaphore.Wait();
    ShowWithSemaphore();
}

 

posted @ 2025-01-13 14:23  Shapley  阅读(15)  评论(0)    收藏  举报