forked from microsoft/qsharp-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SynchronizationContext.cs
41 lines (37 loc) · 1.4 KB
/
SynchronizationContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading;
using Microsoft.Quantum.QsCompiler;
using Microsoft.VisualStudio.Threading;
namespace Microsoft.Quantum.QsLanguageServer
{
/// <summary>
/// Used to enforce in-order processing of the communication with the Q# language server.
/// Such a synchronization context is needed since the Q# language server
/// processes changes incrementally rather than reprocessing entire files each time.
/// </summary>
public class QsSynchronizationContext : SynchronizationContext
{
private readonly AsyncQueue<(SendOrPostCallback, object)> queued = new AsyncQueue<(SendOrPostCallback, object)>();
private void ProcessNext()
{
var gotNext = this.queued.TryDequeue(out (SendOrPostCallback, object) next);
QsCompilerError.Verify(gotNext, "nothing to process in the SynchronizationContext");
if (gotNext)
{
next.Item1(next.Item2);
}
}
/// <inheritdoc/>
public override void Post(SendOrPostCallback fct, object arg)
{
if (fct == null)
{
throw new ArgumentNullException(nameof(fct));
}
this.queued.Enqueue((fct, arg));
this.Send(_ => this.ProcessNext(), null);
}
}
}