如果对象施工过程中您捕获SynchronizationContext
你将能够发送这方面的事件,如果有一个,如果没有背景,然后你的类是建立在这样一个线程在它不关心哪个线程被用来提高事件。这比ISynchronizeInvoke
好,因为SynchronizationContext
将与WinForms,ASP.NET和WPF一起使用,其中ISynchronizeInvoke
仅适用于WinForms。
C#6版本
public class Example
{
private SynchronizationContext _context;
public Example()
{
var existingContext = SynchronizationContext.Current;
_context = existingContext?.CreateCopy() ?? new SynchronizationContext();
}
public virtual event LogEventHandler EntryReceived;
protected virtual void ReceiveEntry(ILogEntry entry)
{
_context.Send(ContextCallback, entry);
}
private void ContextCallback(object entry)
{
EntryReceived?.Invoke(this, new LogEventArgs() { Entry = (ILogEntry)entry });
}
}
C#5和低版本
public class Example
{
private SynchronizationContext _context;
public Example()
{
var existingContext = SynchronizationContext.Current;
_context = existingContext != null ? existingContext.CreateCopy() : new SynchronizationContext();
}
public virtual event LogEventHandler EntryReceived;
protected virtual void ReceiveEntry(ILogEntry entry)
{
_context.Send(ContextCallback, entry);
}
private void ContextCallback(object entry)
{
var temp = EntryReceived;
if (temp != null)
{
temp(this, new LogEventArgs() {Entry = (ILogEntry)entry});
}
}
}