Private Async Function UpdateTableAsync(ByVal tableName As String, ByVal dt As DataTable) As Task Try '対象のテーブルを一括削除。 Using con As New SqlConnection(strConnection) Using cmd As New SqlCommand() Await con.OpenAsync() cmd.Connection = con cmd.CommandText = "DELETE FROM " & tableName cmd.CommandTimeout = 3600 Await cmd.ExecuteNonQueryAsync() con.Close() End Using End Using '対象のテーブルにBulkCopy。 Using con As New SqlConnection(strConnection) Using sqlBulkCopy As New SqlBulkCopy(con) sqlBulkCopy.DestinationTableName = tableName sqlBulkCopy.BulkCopyTimeout = 3600 Await con.OpenAsync() Await sqlBulkCopy.WriteToServerAsync(dt) con.Close() End Using End Using Catch ex As Exception MessageBox.Show(ex.Message) End Try End Function
'対象のテーブルを一括削除。 Private Async Function DeleteTableAsync(ByVal tableName As String) As Task Using con As New SqlConnection(strConnection) Using cmd As New SqlCommand() Await con.OpenAsync().ConfigureAwait(False) cmd.Connection = con cmd.CommandText = "DELETE FROM " & tableName cmd.CommandTimeout = 3600 Await cmd.ExecuteNonQueryAsync().ConfigureAwait(False) con.Close() End Using End Using End Function '対象のテーブルにBulkCopy。 Private Async Function BulkCopyToTableAsync(ByVal tableName As String, ByVal dt As DataTable) As Task Using con As New SqlConnection(strConnection) Using sqlBulkCopy As New SqlBulkCopy(con) sqlBulkCopy.DestinationTableName = tableName sqlBulkCopy.BulkCopyTimeout = 3600 Await con.OpenAsync().ConfigureAwait(False) Await sqlBulkCopy.WriteToServerAsync(dt).ConfigureAwait(False) con.Close() End Using End Using End Function Private Async Function UpdateTableAsync(ByVal tableName As String, ByVal dt As DataTable) As Task Try Await DeleteTableAsync(tableName) Await BulkCopyToTableAsync(tableName, dt) Catch ex As Exception MessageBox.Show(ex.Message) End Try End Function
Private Function UpdateTableAsync(ByVal tableName As String, ByVal dt As DataTable) As Task Dim task1 = DeleteTableAsync(tableName) Dim task2 = task1.ContinueWith(Function (t) BulkCopyToTableAsync(tableName, dt) End Function, TaskContinuationOptions.OnlyOnRanToCompletion).UnWrap() Dim task3 = task1.ContinueWith(Sub (t) MessageBox.Show(t.Exception.Message) End Sub, CancellationToken.None,TaskContinuationOptions.OnlyOnOnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()) Dim task4 = task2.ContinueWith(Sub (t) MessageBox.Show(t.Exception.Message) End Sub, CancellationToken.None,TaskContinuationOptions.OnlyOnOnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext()) Return Task.WhenAll(task3, task4) End Function