C#TAP async多个enqueue Delay然后将所有队列出列

时间:2014-02-27 14:07:57

标签: c# .net-4.5

我有一个系统,其中使用对象调用方法,并且数据库使用具有第一个列表的不同对象编写。

目前:

private async Task SaveAMessage(Messsage message)
{
    var messages = new List<Message>();
    messages.Add(message);
    var envelope = new Envelope();
    envelope.messages = messages;
    await _db.Save(envelope);
}

但我每1秒只能运行_db.Save

TAP的说法是什么:将此项添加到列表中,然后在1秒后将它们全部保存在一起。下面我有一些假代码,表达了我希望我能写的内容

Javascript-y Pseudo Code:

private List<Message> messages = new List<Message>();
private int? valueCheckTimer;
private async Task SaveAMessage(Messsage message)
{
    messages.Add(message);
    if (valueCheckTimer) { 
        return;
    }
    valueCheckTimer = setTimeout(function () {
        var envelope = new Envelope();
        envelope.messages = messages;
        await _db.Save(envelope);
        messages.Clear();
    },1000);
}

如何编写与伪代码一样的C#代码?

2 个答案:

答案 0 :(得分:0)

实际上,您只需进行一次非常简单的改动即可。添加WhenAllSaveAMessage以等待SaveTask.Delay的调用:

private async Task SaveAMessage(Messsage message)
{
    var messages = new List<Message>();
    messages.Add(message);
    var envelope = new Envelope();
    envelope.messages = messages;
    await Task.WhenAll(_db.Save(envelope), Task.Delay(1000));
}

现在你可以循环遍历所有对SaveAMessage的调用,等待它们全部,你可以确定它等到上一次保存完成并且至少已经过了一秒< / em>继续之前。

如果您在其他地方使用SaveAMessage时有时不需要等待一整秒,那么只需将此更改拉出来并使用您用来保存所有消息的任何代码等待{{1}打电话。

答案 1 :(得分:-1)

试试这段c#代码(作为ConsoleApp运行):

namespace ConsoleApplication1
{
    public class Program
    {
        private static async Task<string> SaveAMessage(string message)
        {
            var messages = new List<string>();
            messages.Add(message);
            return await save(messages);
        }

        private static Task<string> save(List<string> msg)
        {
            Task<string> task = Task.Factory.StartNew<string>(() =>
            {
                Console.WriteLine("Message " + msg[0] + " received...");
                Console.WriteLine("Message " + msg[0] + " running...");
                Thread.Sleep(3000);
                return "Message " + msg[0] + " finally return.";
            });
            return task;
        }

        public static void Main(string[] args)
        {
            Task<string> first = SaveAMessage("Msg1");
            first.ContinueWith(x => Console.WriteLine("Print " + x.Result));
            Task<string> second = SaveAMessage("Msg2");
            second.ContinueWith(x => Console.WriteLine("Print " + x.Result));
            Task<string> third = SaveAMessage("Msg3");
            third.ContinueWith(x => Console.WriteLine("Print " + x.Result));
            Task<string> fourth = SaveAMessage("Msg4");
            fourth.ContinueWith(x => Console.WriteLine("Print " + x.Result));
            Task<string> fifth = SaveAMessage("Msg5");
            fifth.ContinueWith(x => Console.WriteLine("Print " + x.Result));
            Console.ReadKey();
        }    
    }
}