以下是一个将Insert
放入数据库表的方法。我在BackGroundWorker线程的DoWork()
内调用此方法。它显然引发了我的“跨线程操作无效......”错误。据我所知,我可以在UI控件上使用Invoke()
方法,如果那些要在DoWork()
内访问。但是这是否意味着以下每个UI控件都应该被调用?有没有更好的方法来实现这一目标?这是否意味着必须在每个UI控件上调用Invoke()方法?
private void AddToOccupations()
{
if (dataGridViewSearch.SelectedRows.Count > 0)
{
foreach (DataGridViewRow datarow in dataGridViewSearch.SelectedRows)
{
try
{
AllocationModel occupation = new AllocationModel()
{
User_ID = userID,
Merge_Status = (int)((MergeStatus)Enum.Parse(typeof(MergeStatus), cmbMergeStatus.SelectedItem.ToString())),
Start_Date = dateTimePickerFROMDate.Value,
Seat_Type = datarow.Cells[2].Value.ToString(),
Occupation_Status = cmbStatus_Type.SelectedItem.ToString(),
Session = datarow.Cells[3].Value.ToString(),
Seat_Number = (Int32)datarow.Cells[0].Value,
Number_of_Guests = (Int32)datarow.Cells[1].Value
};
// Call the service method
var success = this.allocationService.AddToOccupation(occupation);
if (success)
{
// display the message box
MessageBox.Show(
Resources.Add_Occupation_Success_Message,
Resources.Add_Occupation_Success_Title,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
// Reset the screen
//this.Reset();
DoCurrentFreeSearch();
}
else
MessageBox.Show("No Records Inserted!");
}
catch (FormatException ex)
{
errorMessage = "Insert Error: \n";
errorMessage += ex.Message;
MessageBox.Show(errorMessage);
}
}
}
else
MessageBox.Show("Warning! No Row is selected...");
}
这就是我所面对的显而易见的问题。如果我要改变上述方法(基于DML事务的方法的数量),这将会是代码中的巨大变化......您认为什么是替代方法? – bonCodigo
如果您可以将C#5用于您的工作,那么这将成为异步/等待功能的理想候选者。它在代码中的侵入性要小得多。 – Emile
@Emile darn,因为它是,我在4.0,它不会很快上山......现在我看到**为什么** Asynch/Await *首次亮相* ...照顾足以提供给我一个例如,你推荐(在网上)Asynch的例子像我的... – bonCodigo