I have a server that receives files. After receiving file, an event is invoked. It works something like this:
public void Receive() {
// do some file receiving
// decrypt received file
// save file
// when file is received decrypted and saved, invoke event:
OnFileReceived?.Invoke(this, fileName);
}
...
public static event EventHandler<string>? OnFileReceived;
I subscribe to this event in constructor of other class so it fires up a method that opens a file explorer. There is only one instance of that class, so I'm quite sure that event should be invoked only once.
public Foo {
// constructing object
// subscribing to events:
Server.OnFileReceived -= OnFileDownloaded;
Server.OnFileReceived += OnFileDownloaded;
}
...
private void OnFileDownloaded(object? sender, string filename)
{
InfoLabel = "Received: " + filename;
OpenDirectory();
}
The problem is that file explorer is opened twice. I did a little investigation, and it turns out that for some reason my event is being invoked twice in Receive() method. And it drives me nuts.
I tried to fix that first by adding a simple boolean to OnFileDownloaded method:
private void OnFileDownloaded(object? sender, string filename)
{
if (!_isInvoked)
{
_isInvoked = true;
InfoLabel = "Received: " + filename;
OpenDirectory(); // then setting here _isInvoked back to false after closing the File explorer
}
}
But It did not work. I also have tried a solutions found here and here, changing the event declaration:
private EventHandler<string> fileReceived;
public event EventHandler<string> OnFileReceived
{
add
{
if (fileReceived == null || !fileReceived.GetInvocationList().Contains(value))
{
fileReceived += value;
}
}
remove
{
fileReceived -= value;
}
}
Again, with no luck. The question is: How can I prevent this from happening?
Thanks.