惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
InfoQ
博客园_首页
美团技术团队
M
MIT News - Artificial intelligence
人人都是产品经理
人人都是产品经理
Blog — PlanetScale
Blog — PlanetScale
H
Help Net Security
J
Java Code Geeks
T
Tailwind CSS Blog
Jina AI
Jina AI
量子位
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
G
Google Developers Blog
爱范儿
爱范儿
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
宝玉的分享
宝玉的分享
小众软件
小众软件
MongoDB | Blog
MongoDB | Blog
博客园 - 三生石上(FineUI控件)
L
LangChain Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Visual Studio Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - Shapley

项目心得 进程间通讯方式 C#使用MCP协议调用大模型示例 SQL Server LEAD函数实践 sql server行专列一例 数据库字段排序方法两则 Sql Server生成ULID例子 审批流进化记 winform+Task+async 献丑贴:Task.Run中foreach优化 Sql Server Begin TRY sample No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter' has been registered. 某低代码平台自定义控件技术点 Element-plus的el-date-picker控件动态切换中英文方案 Chrome浏览器无法查看页面跳转前的请求日志及解决办法 element-plus上传视频并生成缩略图(封面)方案 JWT自动刷新草案 Ajax方法POST的两种提交方式 H5项目在微信浏览器运行实录 Sql Server变量声明及使用技巧 修改Dify的Nginx对外访问端口 Task实战 asp.net core 9.0发布centos7.9 Barrier CountdownEvent
Task with Console(with SemaphoreSlim)
Shapley · 2025-01-13 · via 博客园 - Shapley

背景:
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();
}