UniTask icon indicating copy to clipboard operation
UniTask copied to clipboard

How to create and immediately schedule UniTask from other thread or regular Task in thread pool.

Open hellozyemlya opened this issue 2 years ago • 1 comments

Assuming I have following code:

        public void Start()
        {
            Task.Run(RegularTask);
            
        }
        async Task RegularTask()
        {
            Debug.Log($"RegularTask before loop {Thread.CurrentThread.ManagedThreadId}");
            while (true)
            {
                Debug.Log($"RegularTask loop {Thread.CurrentThread.ManagedThreadId}");
                await RunUniTask(); 
            } 
        }
        async UniTask RunUniTask()
        {
            Debug.Log($"RunUniTask before yield {Thread.CurrentThread.ManagedThreadId}");
            await UniTask.Yield();
            Debug.Log($"RunUniTask after yield {Thread.CurrentThread.ManagedThreadId}");
        }

This code "switches" RegularTask to main thread after Yield awaited, and first pring of "before yield" happens in thread pool. How I can ensure that RunUniTask starts its execution in main thread and not touching RegularTask(keep it running in previous thread pool or previous synchronization context)?

With regular tasks I can use TaskFactory and specify synchronization context manually, but how I can do this with UniTask?

hellozyemlya avatar Jul 02 '22 10:07 hellozyemlya

Waiting in a previous thread (thread pool) is not possible, even in Task or SynchronizationContext. If you want to wait on SynchronizationContext, you can use SwitchToSynchronizationContext.

neuecc avatar Jul 21 '22 10:07 neuecc

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] avatar Oct 20 '22 00:10 github-actions[bot]