0

Can this code provocate a deadlock? I am afraid that the handler is executed suddenly in the middle of the execution of the DoWork function (which is also locked).

private object lockObject = new object();

public void DoWork()
{
     lock(lockObject) 
     {
         ChannelFactory<TChannel> channelFactory = CreateChannelFactory();
         channelFactory.Faulted += (sender, e) => OnChannelFactoryFaulted(sender, e);
         // Some code.. access to dictionary...
     }
}

 private void OnChannelFactoryFaulted(object sender, EventArgs e)
 {
     lock (lockObject)
     {
        // Some code.. access to dictionary..
     }
 }

Thanks

Cadmi
  • 53
  • 1
  • 7
  • 1
    There are two possibilities here: `Faulted` is raised on the thread that's executing `DoWork`, or it's raised on a different thread. If it's raised on the same thread, that obviously can't happen until after `DoWork` returns, after the lock has been released. If it's raised on a different thread, it will get stuck on the `lock` statement until `DoWork` releases the lock – canton7 May 18 '20 at 14:03
  • Please, refer this link https://stackoverflow.com/q/5035126/12833205. Does it answer your question? – Iliar Turdushev May 18 '20 at 14:05
  • Yes, thank you @IliarTurdushev :) So it looks that your answer canton7 is not correct – Cadmi May 18 '20 at 14:49
  • @Cadmi Why do you think I'm not correct? `lock` is recursive, they're absolutely right: but you never try to acquire the lock recursively. If you called `OnChannelFactoryFaulted` from inside the lock on `DoWork` (on the same thread) the recursiveness becomes relevant, but as I explained, that can't happen in your code. – canton7 May 19 '20 at 08:09
  • @canton7 what I don't understand from what you said in your first comment: "If it's raised on the same thread, that obviously can't happen until after DoWork returns,". Why isn't possible that if raised on the same thread the handler is completely executed and then the DoWork continues exactly from where the handler was triggered? – Cadmi May 19 '20 at 13:47
  • @Cadmi How can it be raised on the thread that's executing DoWork, while DoWork is executing, if `DoWork` never calls into it? If the code in `// Some code.. access to dictionary...` never causes `Faulted` to be raised (and you just say that it accesses a dictionary), then `Faulted` can't be raised until at least `DoWork` exist. If a thread is executing code, it can't randomly jump to another bit of code – canton7 May 19 '20 at 14:39

0 Answers0