我有一個在線程池中執行的委託。計數作爲變量正確傳遞,但是,當程序返回輸出時,傳入的初始值現在是更新後的版本。我如何修改這些變量以保持正確的值?線程安全,防止變量更新
private void SetControlText(TextBox TB, string txt)
{
if (TB.InvokeRequired)
{
Invoke((MethodInvoker)delegate
{
TB.AppendText(txt + "\n");
TB.Update();
});
return;
}
TB.Text = txt;
}
private void DoWork(OCAdapter.OCAdapter Adapter, OutputForm output, int c, object ThreadContext = null)
{
int count = c;
//output.AppendToOutput("Initializing Adapter: " + count + " Test\n");
SetControlText(output.OutputBx, "Initializing Adapter: " + count + " Test\n");
try
{
var Test = Adapter.GetBookmarks();
if (Test != null)
//output.AppendToOutput("Adapter: " + count + " is valid\n");
SetControlText(output.OutputBx, "Adapter: " + count + " is valid\n");
}
catch (Exception ex)
{
//output.AppendToOutput("Exception occured on adapter: " + count + " Exception: " + ex.Message);
SetControlText(output.OutputBx, "Exception occured on adapter: " + count + " Exception: " + ex.Message);
}
}
你怎麼稱呼DoWork? – JeffRSon 2013-05-07 20:45:09
我不確定要理解,也許需要更多一點的代碼?如果你希望'DoWork'在另一個線程傳遞給''SetControlText'時不被另一個線程中斷,那麼你應該用'lock'聲明來包圍你的方法體:http://msdn.microsoft.com/en- us/library/c5kehkcz(v = vs.71).aspx雖然我不確定這是你的問題。 – 2013-05-07 21:12:07