我有一个在线程池中执行的委托。计数作为变量正确传递,但是,当程序返回输出时,传入的初始值现在是更新版本。如何修改这些变量保持正确的值?
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);
}
}
答案 0 :(得分:1)
嘿我实际上找到了答案,线程正在使用共享内存,所以他们在增加后访问变量。
我修复此问题的方法是通过传入带有计数的临时变量。
答案 1 :(得分:0)
你的SetControlText()不太正确。它正在做一个Invoke(),并且还从错误的线程直接设置Text,直接在它下面;每一次。
尝试这样的事情,看看问题是否消失:
private delegate void SetControlTextDelegate(TextBox TB, string txt);
private void SetControlText(TextBox TB, string txt)
{
if (TB.InvokeRequired)
{
TB.Invoke(new SetControlTextDelegate(SetControlText), new object[] { TB, txt });
}
else
{
TB.AppendText(txt + Environment.NewLine);
}
}