我有这样的代码:
public void IssueOrders(List<OrderAction> actions)
{
foreach (var action in actions)
{
if (action is AddOrder)
{
uint userId = apiTransactions.PlaceOrder((action as AddOrder).order);
Console.WriteLine("order is placing userId = " + userId);
}
// TODO: implement other actions
}
// how to wait until OnApiTransactionsDataMessageReceived for all userId is received?
// TODO: need to update actions with received data here
}
private void OnApiTransactionsDataMessageReceived(object sender, DataMessageReceivedEventArgs e)
{
var dataMsg = e.message;
var userId = dataMsg.UserId;
apiTransactions.PlaceOrder
是异步的,所以我会收到userId
结果,但我会在回调 OnApiTransactionsDataMessageReceived 中接收数据。
例如,如果我下了 3 个订单,我将收到 3 个 userId,例如1
、3
和4
。现在我需要等到收到所有这些 userId 的数据。
userId
如果这很重要,它总是在增加。这几乎是整数序列,但由于并行执行,可能会省略一些数字。
升级版注意事项:
- IssueOrders 可以从不同的线程并行执行
- callack 可以在 PlaceOrder 返回之前被调用
UPD2
可能我需要重构下面的 PlaceOrder 代码,以便我可以保证userId
在收到“回调”之前知道它:
public uint PlaceOrder(Order order)
{
Publisher pub = GetPublisher();
SchemeDesc schemeDesc = pub.Scheme;
MessageDesc messageDesc = schemeDesc.Messages[0]; //AddMM
FieldDesc fieldDesc = messageDesc.Fields[3];
Message sendMessage = pub.NewMessage(MessageKeyType.KeyName, "FutAddOrder");
DataMessage smsg = (DataMessage)sendMessage;
uint userId = counter.Next();
FillDataMessageWithPlaceOrder(smsg, order, userId);
System.Console.WriteLine("posting message dump: {0}", sendMessage);
pub.Post(sendMessage, PublishFlag.NeedReply);
sendMessage.Dispose();
return userId;
}
所以我需要将 PlaceOrder 拆分为两种方法:userId CreateOrder
和void PostOrder
. 这将保证当收到回调时我知道userId
。