我有一个父表单AddEmployee,它调用类Worker,类打开另一个(子)表单InformationFetching。我想将AddEmployee设置为InformationFetching的父形式,但是我得到了交叉线程的错误。
//Parent Form
public partial class AddNewAccount : DevExpress.XtraEditors.XtraForm
{
Thread thrd;
private void brnContinue_Click(object sender, EventArgs e)
{
Worker workerObject = new Worker(this);
//ThreadStart ts = new ThreadStart(workerObject.DoWork);
//thrd = new Thread(ts);
Thread thrd = new Thread(() =>
{
//workerObject.DoWork(); // CrossThreadException
Invoke(new MethodInvoker(workerObject.DoWork)); // OK
});
//some code here
addNewAccount();
}
private void addNewAccount()
{
//parameter define here and pass in verifyDetails
thrd.Start();
validatorClass objClass = new validatorClass();
Bool isSuccess = false;
isSuccess = objClass.verifyDetails(parameters); //it will verify all the details. May take upto a 30 seconds
}
}
//worker class
public class Worker
{
Form parentForm
InformationFetching frmChild;
Bool isTestCall = false;1
public Worker(Form prntForm)
{
// TODO: Complete member initialization
parentForm = prntForm;
}
public void DoWork()
{
//child form
if(isTestCall)
InformationFetching frmChild = new InformationFetching(0)
else
InformationFetching frmChild = new InformationFetching(1) //1 is when small verification
//getting error of cross-thread
frmChild.MdiParent = parentForm;
frmChild.StartPosition = FormStartPosition.CenterParent;
frmChild.ShowDialog();
}
}
//validator class
public class validatorClass
{
// verify all the details one by one and fetch in InformationFetching form
internal void verifyDetails()
{
//phase-1 verification
AccountSyncform().showInfo("Information");
//phase-2 verification
AccountSyncform().showInfo("Information");
//phase-3 verification
AccountSyncform().showInfo("Information");
//phase-4 verification
AccountSyncform().showInfo("Information");
//phase-5 verification
AccountSyncform().showInfo("Information");
}
public InformationFetching AccountSyncform()
{
InformationFetching mForm = null;
try
{
foreach (System.Windows.Forms.Form f in System.Windows.Forms.Application.OpenForms)
if (f.Name == "InformationFetching")
{ mForm = (InformationFetching)f; break; }
}
catch (Exception ex)
{
MainTainErrorLog.addGeneralErrorToLog(ex.Message);
}
return mForm;
}
}有人能告诉我我在这里错过了什么吗?
发布于 2016-06-29 14:43:06
根据评论,我建议如下:
private void brnContinue_Click(object sender, EventArgs e)
{
Worker workerObject = new Worker(this);
Thread thrd = new Thread(() =>
{
Invoke(new MethodInvoker(delegate
{
addNewAccount(); // Do something heavy for 30s
workerObject.DoWork();
}));
});
thrd.Start();
}
private void addNewAccount()
{
validatorClass objClass = new validatorClass();
bool isSuccess = false;
isSuccess = objClass.verifyDetails(parameters);
}https://stackoverflow.com/questions/38102841
复制相似问题