本文整理汇总了C#中System.Threading.SynchronizationContext.SetSynchronizationContext方法的典型用法代码示例。如果您正苦于以下问题:C# SynchronizationContext.SetSynchronizationContext方法的具体用法?C# SynchronizationContext.SetSynchronizationContext怎么用?C# SynchronizationContext.SetSynchronizationContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.SynchronizationContext
的用法示例。
在下文中一共展示了SynchronizationContext.SetSynchronizationContext方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
/// <summary>
/// Starts this <see cref="MicroThread"/> with the specified function.
/// </summary>
/// <param name="microThreadFunction">The micro thread function.</param>
/// <param name="flags">The flags.</param>
/// <param name="scheduleMode">The schedule mode.</param>
/// <exception cref="System.InvalidOperationException">MicroThread was already started before.</exception>
public void Start(Func<Task> microThreadFunction, ScheduleMode scheduleMode = ScheduleMode.Last)
{
ScriptId = microThreadFunction.Target.GetType().Name;
// TODO: Interlocked compare exchange?
if (Interlocked.CompareExchange(ref state, (int)MicroThreadState.Starting, (int)MicroThreadState.None) != (int)MicroThreadState.None)
throw new InvalidOperationException("MicroThread was already started before.");
Action wrappedMicroThreadFunction = async () =>
{
try
{
State = MicroThreadState.Running;
await microThreadFunction();
if (State != MicroThreadState.Running)
throw new InvalidOperationException("MicroThread completed in an invalid state.");
State = MicroThreadState.Completed;
}
catch (OperationCanceledException e)
{
// Exit gracefully on cancellation exceptions
SetException(e);
}
catch (Exception e)
{
Scheduler.Log.Error("Unexpected exception while executing a micro-thread. Reason: {0}", new object[] {e});
SetException(e);
}
finally
{
lock (Scheduler.allMicroThreads)
{
Scheduler.allMicroThreads.Remove(AllLinkedListNode);
}
}
};
Action callback = () =>
{
SynchronizationContext = new MicroThreadSynchronizationContext(this);
SynchronizationContext.SetSynchronizationContext(SynchronizationContext);
wrappedMicroThreadFunction();
};
lock (Scheduler.allMicroThreads)
{
Scheduler.allMicroThreads.AddLast(AllLinkedListNode);
}
ScheduleContinuation(scheduleMode, callback);
}