1Task.Factory.StartNew((args) =>2{3 string serverName = (string)((object[])args)[0];4 string userName = (string)((object[])args)[1];5 string pwd = (string)((object[])args)[2];6 string dbName = (string)((object[])args)[3];7 Exception exc;8 bool rc = SQLServerDbConnectionInfo.CheckConnection(serverName, userName, pwd, dbName, out exc);9 return new object[] { rc, exc?.Message, dbName, serverName, userName };10}, new object[] { this.ServerName, this.UserName, this.Password, this.DatabaseName }).ContinueWith((t) =>11{12 this.IsBusy = false;13 if (!t.IsCompleted || t.IsFaulted || !(bool)t.Result[0])14 {15 StringBuilder sb = new StringBuilder();16 sb.AppendFormat((string)WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("myAssembly:Properties.Resources:DBConnectionFailedExtendedMessage", null, WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.Culture), (string)t.Result[2], (string)t.Result[3], (string)t.Result[4]);17 if (!String.IsNullOrEmpty((string)t.Result[1]))18 {19 sb.Append(System.Environment.NewLine);20 sb.AppendLine((string)t.Result[1]);21 }22 var parentWindow = Window.GetWindow(this);23 if (parentWindow == null)24 {25 parentWindow = Application.Current?.MainWindow;26 }27 MessageBox.Show(parentWindow, sb.ToString(), (string)WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("myAssembly:Properties.Resources:ConnectionFailed", null, WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.Culture));28 if (onCompletedAction != null)29 {30 onCompletedAction(false);31 }32 }33 else34 {35 if (showSuccessMsgBox)36 {37 var parentWindow = Window.GetWindow(this);38 if (parentWindow == null)39 {40 parentWindow = Application.Current?.MainWindow;41 }42 MessageBox.Show(parentWindow, (string)WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("myAssembly:Properties.Resources:ConnectionTestSucceeded", null, WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.Culture), null);43 }44 if (onCompletedAction != null)45 {46 onCompletedAction(true);47 }48 }49}, TaskScheduler.FromCurrentSynchronizationContext());
Task.Factory.StartNew
ABSTRACT
Esempio di Task.Factory.StartNew con ContinueWith: verifica in background una connessione a SQL Server e aggiorna l'interfaccia al termine.