/// <summary> /// In this case this event, unlike the event above is called from /// a different thread, without InvokeIfRequired in WinFormsExtensionLibrary /// a exception would be thrown "cross thread operation not valid". /// /// InvokeIfRequired language extension is basic code to check if Invoke /// needs to be called and if so uses Invoke and if not simple executes /// the action, in this case setting Text property of a label. /// /// In DataGridViewLoadDelimitedFileAsynchronous.Form1 Example1Button_Click /// several lines of code are executes as an Action for InvokeIfRequired. /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void Ops_OnIterate2(object sender, ProcessIndexingArgs args) { /* * It's unsafe to call a control directly from a thread that didn't create it which happens * in this case setting ProcessStatus2Label.Text directly, instead the extension method * InvokeIfRequired ensuring thread-safe call is made to ProcessStatus2Label. * * InvokeIfRequired extension method is used in other code samples in this Visual Studio solution. * By using InvokeIfRequired creates uniformity when an Action is required in the calling thread. * */ if (EnableCrossThreadButton.Checked) { ProcessStatus2Label.Text = args.ToString(); } else { ProcessStatus2Label.InvokeIfRequired(d => { ProcessStatus2Label.Text = args.ToString(); }); } }
/// <summary> /// Show progress on code executed in ProcessAsync1Button. Since in this /// example we are not using ConfigureAwait(false) this code executes /// in the same thread so not cross /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnIterateLoop1(object sender, ProcessIndexingArgs args) { ProcessStatus1Label.Text = args.ToString(); }