使用async和await的跨线程异常

时间:2018-01-18 16:26:47

标签: c# multithreading asynchronous async-await

我正在异步调用一堆方法。不知何故,发布版本工作正常,但调试await task1;给了我一个例外:

  

" System.InvalidOperationException:'跨线程操作无效:   Control' comboBox1'从线程以外的线程访问它   是在"

上创建的

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()只有一个引用task1。那么为什么例外?

1 个答案:

答案 0 :(得分:0)

问题在于Task.Factory.StartNew

是的,asyncawait不会创建新主题。但! StartNew可能

你想要做的是让你的getDBdata2TroubleMethod异步,只做

await TroubleMethod()
在TroubleMethod里面做

await getDBdata2()