0

I have a event which in many case fires many times but I want an event to be completed before the next event is ran.

I am trying to create a cryptocurrency trading bot. The event in question is private void CoinInformation_OnNewTradeEvent(object sender, AggregateTradeEventArgs e)

Since that single event fires multiple times, I always thought it would be executed in a synchronous fashion where when one event is running, the next event wont run until this is completed. I tried putting locks but realize that doesnt work.

private void CoinInformation_OnNewTradeEvent(object sender, AggregateTradeEventArgs e)
    {
        lock(myObject)
        {
            try
            {
                Decimal currentTradePrice = e.Trade.Price;

                UpdateSMA(currentTradePrice);

                TryBuy(currentTradePrice);

                TrySell(currentTradePrice);

                TryStopLoss(currentTradePrice);
            }
            catch
            {
                return;
            }


        }

    }
RStyle
  • 875
  • 2
  • 10
  • 29
  • Is `myObject` static? – Pablo notPicasso Mar 11 '19 at 12:01
  • Yes private static object myObject = new Object(); – RStyle Mar 11 '19 at 12:03
  • I saw something similar here but its a async event. Does it make a diff? https://stackoverflow.com/a/22864286/958967 – RStyle Mar 11 '19 at 12:05
  • When you say "the next even won't run", what does that mean? The `lock` doesn't prevent multiple callers from invoking the method concurrently. It only means that threads will wait at the `lock` until the previous invocation releases the lock. – Scott Hannen Mar 11 '19 at 13:37
  • When multiple callers invoke a method concurrently, I thought the first invoked method must complete before the second method is executed. But seems like that is not the case. – RStyle Mar 11 '19 at 13:41
  • Correct. Any number of threads can call the method simultaneously. If there was no `lock`, different threads could be executing different parts of the method at the same time, which can lead to unexpected behaviors unless you account for it. In this case, if one thread acquires the `lock` and then another thread enters that method, it will wait at the `lock` until it is released. You could even end up with multiple threads waiting for the same `lock`. – Scott Hannen Mar 11 '19 at 14:53
  • Oh wait.. is it because my trybuy and trysell are async methods but i never await them ? – RStyle Mar 12 '19 at 05:28

1 Answers1

0

Sorry seems like my TryBuy and TrySell were async and I didnt await them thus there were reentries.

RStyle
  • 875
  • 2
  • 10
  • 29