0

Is it OK to use .ConfigureAwait(false) for the following two code snippets?

Case 1

var ds = new BindingSource();
ds.DataSource = await CallAsync(); // .ConfigureAwait(false);
UIControl.DataSource = ds;

Case 2

UIControl.DataSource = new BindingSource
{
    DataSource = await CallAsync() // .ConfigureAwait(false)
};

Does the first one seem to have the problem of set UI control at the background thread? How about the second one?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • Yes both cases have problem. – Reza Aghaei Mar 02 '19 at 04:45
  • It's not clear why you are considering `ConfigureAwait(false)` in this, well, *context*. Is it about `CallAsync()` not being that much *async*? Are you using `Task.Run()` in the implementation of a not-so-much `async` method? Maybe it's just partially `async`? – Jimi Mar 02 '19 at 15:29

1 Answers1

2

All access to controls should be done in the same thread which the control is created.

By calling ConfigureAwait(false) you are asking not to attempt to marshal the continuation back to the original context captured. It means the code continue the execution in a different context than the UI thread which is invalid operation.

So, the answer is yes, both above cases have problem and will result in:

InvalidOperationException: Cross-thread operation not valid: Control 'Control Name' accessed from a thread other than the thread it was created on.

NGambit
  • 1,141
  • 13
  • 27
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398