当我在ScheduleBackUp()
中调用form_load
时,该方法仅执行两次!
这是我的课程:
class BackupDBs : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly object _lock = new object();
private int _state = -1;
string nameBackupFolder;
public void ScheduleBackUp()
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(1);
var timer = new System.Threading.Timer((e) =>
{
DoBackup();
}, null, startTimeSpan, periodTimeSpan);
}
public int MyState
{
get
{
return _state;
}
set
{
lock (_lock)
{
if (value != _state)
{
_state = value;
NotifyStateChanged("MyState");
}
}
}
}
private void NotifyStateChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void DoBackup()
{
MyState = 0;
try
{
MyState = 1;
MyState = 2;
CreateBackupFolder();
}
catch
{
MyState = 3;
return;
}
try
{
var con = new MainCon();
con.sqlQuery("BACKUP DATABASE [" + DataCenter.DEFAULT_DB_NAME + "] TO DISK='" + nameBackupFolder + "\\" + DataCenter.DEFAULT_DB_NAME + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'");
con.nonQueryEx();
con.closecon();
MyState = 4;
}
catch
{
MyState = 5;
}
}
public void CreateBackupFolder()
{
//couz we need create to each DB special folder so we need to get the descr of default DB
string desc = DataCenter.DEFAULT_DB_DESCRIPTION;
//Get the default path for backup
string pathBackup = DataCenter.BACKUP_PATH;
//Preaper the name for our folder
nameBackupFolder = pathBackup + @"\" + "backup for " + desc;
// Create a new target folder, if not exists.
if (!System.IO.Directory.Exists(nameBackupFolder))
{
System.IO.Directory.CreateDirectory(nameBackupFolder);
}
}
我用它来调用方法:
private Classes.BackupDBs budb = new Classes.BackupDBs();
budb.ScheduleBackUp();
仅发生两次成功的备份,然后什么也没有发生。 请问我想念什么?
答案 0 :(得分:0)
您只需要将timer
的声明移至表单字段,这样就不会超出范围并可以回收。
您的字段应如下所示:
public event PropertyChangedEventHandler PropertyChanged;
private readonly object _lock = new object();
private int _state = -1;
string nameBackupFolder;
System.Threading.Timer timer;
现在在ScheduleBackup()
中,执行:
timer = new System.Threading.Timer((e) =>
{
DoBackup();
}, null, startTimeSpan, periodTimeSpan);
现在它将永远有效。