Closed tqk2811 closed 1 year ago
In one AT device, we have two thread. And it not good for so much device (ex: 100 devices).
So we can use 8-16 thread with SynchronizationContext for 100 devices
public void Open(SynchronizationContext synchronizationContext = null)
{
if (synchronizationContext != null)
{
reader = synchronizationContext.PostAsync(() => ReadPipeAsync(pipe, cancellationTokenSource.Token));
}
else
{
reader = Task.Factory.StartNew(() => AsyncContext.Run(() => ReadPipeAsync(pipe, cancellationTokenSource.Token)), TaskCreationOptions.LongRunning);
}
}
List<SynchronizationContext> _SynchronizationContextPool = new List<SynchronizationContext>();
async void MainLoopSynchronizationContextPool()
{
lock (_SynchronizationContextPool) _SynchronizationContextPool.Add(SynchronizationContext.Current);
while (true) await Task.Delay(10);
}
for (int i = 0; i < Environment.ProcessorCount; i++)
{
Task.Factory.StartNew(() => AsyncContext.Run(MainLoopSynchronizationContextPool), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
await Task.Delay(1000);
for(int i = 0; devices.Count; i++)
{
//..........
atChannel.Open(_SynchronizationContextPool[ i % _SynchronizationContextPool.Count ]);
}
https://github.com/hbjorgo/ATLib/blob/f50942650a74b25f26d4d6ba989668371a946171/src/HeboTech.ATLib/Parsers/AtReader.cs#L32 https://github.com/hbjorgo/ATLib/blob/f50942650a74b25f26d4d6ba989668371a946171/src/HeboTech.ATLib/Parsers/AtChannel.cs#L62
Task.Factory.StartNew
with flagLongRunning
will create newTask
and run in newThread
(not run inThreadPool
)But you use
async
await
withoutSynchronizationContext
will makeReadPipeAsync
run inThreadPool
afterawait
if await another task run in different thread.In current, it work ok (maybe not) because
PipeReader.ReadAsync
not in the case (depends on input stream).It may not work in the future if the library changes or modifies the code or specific stream input, so please keep this in mind if you modify the code or update the library.
Suggested Install Nito.AsyncEx.Context