我怎么异步处理消息,扔掉任何新邮件,而处理? [英] how do I handle messages asynchronously, throwing away any new messages while processing?

查看:156
本文介绍了我怎么异步处理消息,扔掉任何新邮件,而处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有赞同的值更新我们的邮件系统上的主题的C#应用​​程序。当一个新的价值在于,我做一些处理再进行。问题是,更新可以来比应用程序能够处理他们更快。我想要做的就是牵住到最新的价值,所以我不想要一个队列。例如,源公布值1和我的应用程序接收它;同时,加工,源出版序列(2,3,4,5)之前,我的应用程序进行处理;我的应用程序,然后处理值5,随着扔掉前值。

I have a C# app that subscribes to a topic on our messaging system for value updates. When a new value comes in, I do some processing and then carry on. The problem is, the updates can come faster than the app can process them. What I want to do is to just hold on to the latest value, so I don't want a queue. For example, the source publishes value "1" and my app receives it; while processing, the source publishes the sequence (2, 3, 4, 5) before my app is done processing; my app then processes value "5", with the prior values thrown away.

这是一种很难,因为它是基于专有消息库来发布工作的代码示例,但我认为这是一个常见的模式,我只是无法弄清楚它叫什么......这似乎是处理函数必须比在消息回调一个单独的线程运行,但我不知道如何组织这个,例如:线程是如何通知的价值变动。 ?什么我需要做的任何一般提示

It's kind of hard to post a working code sample since it's based on proprietary messaging libraries, but I would think this is a common pattern, I just can't figure out what it's called...It seems like the processing function has to run on a separate thread than the messaging callback, but I'm not sure how to organize this, e.g. how that thread is notified of a value change. Any general tips on what I need to do?

推荐答案

一个非常简单的方法可能是这样的:

A very simple way could be something like:

private IMessage _next;

public void ReceiveMessage(IMessage message)
{
    Interlocked.Exchange(ref _next, message);
}

public void Process()
{
    IMessage next = Interlocked.Exchange(ref _next, null);

    if (next != null)
    {
        //...
    }
}

这篇关于我怎么异步处理消息,扔掉任何新邮件,而处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆