// Copyright © 2021 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
//Originally based on https://github.com/CefNet/CefNet.DevTools.Protocol/blob/0a124720474a469b5cef03839418f5e1debaf2f0/CefNet.DevTools.Protocol/Internal/EventProxy.T.cs
using System;
using System.IO;
using System.Threading;
namespace CefSharp.DevTools
{
///
/// Generic Typed Event Proxy
///
/// Event Args Type
internal class EventProxy : IEventProxy
{
private event EventHandler handlers;
private Func convert;
///
/// Constructor
///
/// Delegate used to convert from the Stream to event args
public EventProxy(Func convert)
{
this.convert = convert;
}
///
/// Add the event handler
///
/// event handler to add
public void AddHandler(EventHandler handler)
{
handlers += handler;
}
///
/// Remove the event handler
///
/// event handler to remove
/// returns true if the last event handler for this proxy was removed.
public bool RemoveHandler(EventHandler handler)
{
handlers -= handler;
return handlers == null;
}
///
public void Raise(object sender, string eventName, Stream stream, SynchronizationContext syncContext)
{
stream.Position = 0;
var args = convert(eventName, stream);
if (syncContext == null)
{
handlers?.Invoke(sender, args);
}
else
{
syncContext.Post(new SendOrPostCallback(state =>
{
handlers?.Invoke(sender, args);
}), null);
}
}
///
public void Dispose()
{
handlers = null;
}
}
}