Skip to content

Commit e5fa91a

Browse files
committed
Use ConcurrentQueue in MainThreadSynchronizationContext.
1 parent 50b1a09 commit e5fa91a

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

src/com.unity.editor.tasks/Editor/Schedulers/MainThreadSynchronizationContext.cs

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ namespace Unity.Editor.Tasks
66
using Helpers;
77

88
#if UNITY_EDITOR
9-
using System.Collections.Generic;
9+
using System.Collections.Concurrent;
1010
using UnityEditor;
1111

1212
public class MainThreadSynchronizationContext: SynchronizationContext, IMainThreadSynchronizationContext
1313
{
14-
readonly Queue<Action> m_Callbacks = new Queue<Action>();
14+
private readonly ConcurrentQueue<Action> m_Callbacks = new ConcurrentQueue<Action>();
1515

1616
public MainThreadSynchronizationContext(CancellationToken token = default)
1717
{
@@ -34,24 +34,22 @@ public override void Post(SendOrPostCallback d, object state)
3434
if (d == null)
3535
return;
3636

37-
lock (m_Callbacks)
38-
m_Callbacks.Enqueue(() => d(state));
37+
m_Callbacks.Enqueue(() => d(state));
3938
}
4039

4140
void Update()
4241
{
43-
Queue<Action> callbacks;
44-
45-
lock (m_Callbacks)
42+
while (m_Callbacks.TryDequeue(out var callback))
4643
{
47-
if (m_Callbacks.Count == 0)
48-
return;
49-
callbacks = new Queue<Action>(m_Callbacks);
50-
m_Callbacks.Clear();
44+
try
45+
{
46+
callback();
47+
}
48+
catch
49+
{
50+
// Ignore exceptions.
51+
}
5152
}
52-
53-
foreach (var callback in callbacks)
54-
callback();
5553
}
5654
}
5755
#else

0 commit comments

Comments
 (0)