-1

I have a WPF application that makes use of a resource. This resource can be used in two ways:

  • IU events. When the user clicks on different elements of the view, it writes a value.
  • On a background task. Periodically, readings of various values are made.

I have problems when a reading is in progress and the user has to do a writing. I want to stack the calls to the resource methods in order to execute them sequentially.

These are resource's methods:

  • async Task <bit []> ReadBitsAsync (byte id)
  • async Task <ushort []> ReadUshortsAsync (byte id)
  • async Task WriteBitAsync (byte id, ushort position, bool value)
  • async Task WriteUshortAsync (byte id, ushort position, ushort value)

I've tried doing it with the lock statement, but you can't await a task inside a lock statement.

Is there any way to stack these method calls with all parameter values?

Jon
  • 891
  • 13
  • 32
  • @Servy This is not what I was asking, but it is what I wanted to do previously. Sorry for the duplicate. – Jon Oct 31 '17 at 07:57

2 Answers2

0

Put all the commands/actions for a resource in a queue and have a single thread process this queue. If you want write/user actions to take precedence, do not use a queue but use a list instead and add these actions to the top.

Emond
  • 50,210
  • 11
  • 84
  • 115
0

I've tried doing it with the lock statement, but you can't await a task inside a lock statement.

If you use a SemaphoreSlim, you could even "lock" asynchronously:

SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);

await semaphore.WaitAsync(); //acquire "lock"
try
{
    //...
    await DoSomethingAsync();
}
finally
{
    semaphore.Release(); //release "lock"
}
mm8
  • 163,881
  • 10
  • 57
  • 88