在C#中使用线程异步执行语句

时间:2019-01-16 22:26:11

标签: c# multithreading

我正在使用以下代码异步执行我的代码- 使用Thread.Join()以便asyncdelete完成后才启动asyncCreateIndex()。 这段代码可以正常工作,但我相信会有更好的方法

1. I am using two threads, can this below operation not be done using 1 thread or something similar - 

DoSomething(); //Once this finishes start executing below things async
Thread thread = new Thread(() => AsyncDelete(objectFileInfo.FullName));
thread.Start();
thread.Join(); // Wait till asyncdelete() completes
Thread threadIndex = new Thread(() => AsyncCreateIndex(destFileName, false, RepNum, EntityType, Domain, Org, EntityValue, bufferData));
threadIndex.Start();

1 个答案:

答案 0 :(得分:0)

如果使方法异步:

async Task AsyncDelete(string name)
{
    var cmd = new SqlCommand
    {
        //Initialize here
    };
    await cmd.ExecuteNonQueryAsync();
}

那么您就可以等他们:

DoSomething(); 
await AsyncDelete(objectFileInfo.FullName);
await AsyncCreateIndex(destFileName, false, RepNum, EntityType, Domain, Org, EntityValue, bufferData);

不需要单独的线程。