如果對象施工過程中您捕獲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});
}
}
}