小编use*_*663的帖子

异步/等待或任务。在控制台应用程序/ Windows服务中运行

我一直在研究(包括查看此主题的所有其他SO帖子)实现(最可能的)Windows Service worker的最佳方法,该服务将从数据库中提取工作项并在“解雇后-forget'方式在后台进行(工作项管理全部以异步方法处理)。工作项将是Web服务调用和数据库查询。这些工作项的生产者将受到一些限制,以确保某种可衡量的方法来安排工作。下面的示例非常基础,仅用来突出while循环和for循环的逻辑。哪种方法比较理想或没关系?有没有更合适/更有效的方法来实现这一目标?

异步/等待...

    private static int counter = 1;

    static void Main(string[] args)
    {
        Console.Title = "Async";

        Task.Run(() => AsyncMain());

        Console.ReadLine();            
    }

    private static async void AsyncMain()
    {
        while (true)
        {
            // Imagine calling a database to get some work items to do, in this case 5 dummy items
            for (int i = 0; i < 5; i++)
            {
                var x = DoSomethingAsync(counter.ToString());

                counter++;
                Thread.Sleep(50);
            }

            Thread.Sleep(1000);
        }
    }

    private static async Task<string> DoSomethingAsync(string jobNumber)
    {
        try
        {
            // …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous task-parallel-library async-await

5
推荐指数
1
解决办法
4108
查看次数