using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Runtime.InteropServices; namespace mainProgram { public partial class RadCorrectionWindow : Form { private BackgroundWorker backgroundWorker1; private ProjectManager mProjectManager = null;//保存打开的/新建的工程对象 public RadCorrectionWindow(ProjectManager projectManager) { InitializeComponent(); mProjectManager = projectManager; } private void CancelBtn_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; Close(); } private void StartProcessBtn_Click(object sender, EventArgs e) { var addr2 = getMemory(mProjectManager); Console.WriteLine("子窗口变量的地址 = " + addr2); //mProjectManager.UpdateProgressBarInfo = new UpdateProgressBarInfoDelegate(UpdateWidgetInfo); mProjectManager.UpdateProgressBarInfoEvent += UpdateWidgetInfo;//向事件中注册事件处理程序 //mProjectManager.RadComplete = new RadCompleteDelegate(RadComplete); mProjectManager.RadCompleteEvent += RadComplete; Thread t1 = new Thread(new ThreadStart(mProjectManager.Rad)); t1.IsBackground = true; t1.Start(); } public void UpdateWidgetInfo(int ipos, string vinfo)// { //ProcessesDetailTextBox.AppendText(vinfo);//此行代码放在这里会出现问题 → 线程间操作无效: 从不是创建控件“ProcessesDetailTextBox”的线程访问它。 if (this.InvokeRequired) //InvokeRequired属性为真时,说明一个创建它以以外的线程(即SleepT)想访问它 { UpdateProgressBarInfoDelegate setpos = new UpdateProgressBarInfoDelegate(UpdateWidgetInfo); this.Invoke(setpos, new object[] { ipos, vinfo });//SleepT线程调用本控件Form1中的方法 } else { this.progressBar1.Value = Convert.ToInt32(ipos); ProcessesDetailTextBox.AppendText(vinfo); } } public void RadComplete() { //this.Close();//此行代码放在这里会出现问题 → 线程间操作无效: 从不是创建控件“RadCorrectionWindow”的线程访问它。 if (this.InvokeRequired)//InvokeRequired属性为真时,说明一个创建它以以外的线程想访问它 { RadCompleteDelegate RadCompleteTmp = new RadCompleteDelegate(RadComplete); this.Invoke(RadCompleteTmp, new object[] { }); } else { MessageBox.Show(this, "辐亮度转换完成!", "提示"); this.DialogResult = DialogResult.OK; this.Close(); } } public string getMemory(object o) // 获取引用类型的内存地址方法 { GCHandle h = GCHandle.Alloc(o, GCHandleType.WeakTrackResurrection); IntPtr addr = GCHandle.ToIntPtr(h); return "0x" + addr.ToString("X"); } } }