I need to loop through all my databases in a TreeView, then choose TreeNode for the database name to restore. My code works fine if I choose only 1, 2 or 3 databases to restore. But if I choose many databases it will get hung.
Please check my code and help me..
foreach (TreeNode tn in trvList.Nodes)
{
if (tn.Checked == true)
{
strFileName = GetFileTorestor(strRealdb);//Check File Directory to restore example : C:data\tn.text.
if (strFileName != "")
{
RestoreDatabase(res, tn);
}
else
{
strErorLog += "\r\n -" + tn.Text;
blIsEror = true;
MessageBox.Show("Database " + tn.Text + " has not found!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
/// <summary>
/// Restore database according to treenode selected.
/// </summary>
/// <param name="res"></param>
/// <param name="tn"></param>
private void RestoreDatabase(Restore res,TreeNode tn)
{
res.Database = tn.Text;
res.Action = RestoreActionType.Database;
res.Devices.AddDevice(strFileName, DeviceType.File);
res.ReplaceDatabase = true;
this.pgrRestore.Value = 0;
this.pgrRestore.Maximum = 100;
//res.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
res.PercentCompleteNotification = 5;
res.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);
res.SqlRestore(DBHelper.Server);
stLog += "\r\n " + tn.Text + " from file " + strFileName;//Record database name already restore to log text
txtLog.Text = stLog;
txtLog.Refresh();
}
If you mean by stuck that the UI freezes for a while then that is because you are excuting your work on the main thread which is the UI thread. No UI interaction is possible as the thread is busy doing your work. You should have a look at
BackgroundWorkerto perform your work in the background and report progress to the UI.