1

I am calling a bunch of methods asynchronously. Somehow the release version works fine but while debugging await task1; gives me an exception:

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

on line comboBox1.ValueMember = "value member";

async private void CallingMethod()
{
    Task task1 = Task.Factory.StartNew(TroubleMethod);
    Task task2 = Task.Factory.StartNew(Method1);
    var task3 = Task.Factory.StartNew(() => Method2(Param1));
    //other tasks
    //other stuff

    await task3;
    await task2;
    await task1;
}

private void TroubleMethod()
{
    class1 thedata = getDBdata();

    comboBox1.DataSource = thedata;
    comboBox1.DisplayMember = "display member";
    comboBox1.ValueMember = "value member";

    class2 thedata2 = getDBdata2();

    comboBox2.DataSource = thedata2;
    comboBox2.DisplayMember = "display member2";
    comboBox2.ValueMember = "value member2";
}

TroubleMethod() has only one reference which is task1. So why the exception?

  • You have to update controls on the UI thread. You can use [Invoke()](https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx) to do it from a different thread. – itsme86 Jan 18 '18 at 16:29
  • 1
    `Task.Factory.StartsNew()` takes a thread from the thread-pool and executes the method on that thread. But you can/should not access your UI controls from a different thread than the UI thread. – René Vogt Jan 18 '18 at 16:30
  • wrap the code that accesses the UI controls in a Dispatcher.Invoke block – Jon Jan 18 '18 at 16:39

1 Answers1

0

problem lies on Task.Factory.StartNew

Yes its true that async and await does NOT create new thread. But! StartNew might

what you would want to do is to make your getDBdata2 and TroubleMethod async and just do

await TroubleMethod()

inside TroubleMethod do

await getDBdata2()
Steve
  • 11,696
  • 7
  • 43
  • 81
  • .. and not `void` – Crowcoder Jan 18 '18 at 16:31
  • Thanks Steve I tried your solution. But it gives me an error on 'comboBox1.DataSource = thedata;' saying "System.ArgumentException: 'Complex DataBinding accepts as a data source either an IList or an IListSource.'" I found a solution but somehow I can't post on this thread anymore. – Anjani Kumar Agrawal Jan 18 '18 at 19:10
  • @AnjaniKumarAgrawal that's another issue, basically your class1 has to implement IList or IListSource interface. Or you can just use a regular list instead. – Steve Jan 18 '18 at 19:22