The SpicyPixel.Threading.Unity.dll assembly provides functionality to integrate the Fiber and Task features of the Concurrency Kit with the Unity coroutine scheduler.
MonoBehaviour Extensions
Using ConcurrentBehaviour
The ConcurrentBehavior class extends MonoBehaviour with additional properties to make it easy to access the scheduler associated with the behaviour.
public class MyBehaviour : ConcurrentBehaviour
{
override void Awake()
{
base.Awake();
}
void Update()
{
taskFactory.StartNew(() => DoWorkOnUnityThread()).
ContinueWith((t) => DoMoreWorkOnUnityThread(), taskScheduler);
}
}
Managing scheduler creation
If it is not convenient to extend your behaviour from ConcurrentBehavior, you can create factory and scheduler instances by invoking one of the extension methods in UnityTaskExtensions.
public class MyBehaviour : MonoBehaviour
{
private TaskFactory customTaskFactory;
void Awake()
{
customTaskFactory = this.CreateTaskFactory();
}
void Update()
{
customTaskFactory.StartNew(() => DoWorkOnUnityThread()).
ContinueWith((t) => DoMoreWorkOnUnityThread(), customTaskFactory.Scheduler);
}
}
Shared factory
You can use UnityTaskFactory to access a shared factory instance which ultimately relies on the shared ConcurrentBehavior instance.
public class MyBehaviour : MonoBehaviour
{
void Update()
{
UnityTaskFactory.Default.StartNew(() => DoWorkOnUnityThread()).
ContinueWith((t) => DoMoreWorkOnUnityThread(), UnityTaskScheduler.Default);
}
}
Synchronization Context
The UnitySynchronizationContext is a convenient way to integrate with code which relies on a SynchronizationContext or to post operations back to the calling thread in a scheduler agnostic manner.
public class MyBehaviour : MonoBehaviour
{
void Awake()
{
SynchronizationContext.SetSynchronizationContext(
UnitySynchronizationContext.SharedInstance);
}
void ProcessResults()
{
var syncContext = SynchronizationContext.Current;
new Timer(TimerCallback, syncContext, TimeSpan.FromSeconds(3), TimeSpan.Zero);
}
void TimerCallback(object state)
{
var syncContext = state as SynchronizationContext;
syncContext.Send((moreState) => {
Debug.Log("Back on the Unity thread");
}, null);
}
}