我有这段代码
private delegate void InvokeDelegate();
private void OpenFormNewNote(object sender, FileSystemEventArgs e)
{
if(loop == 2)
{
string service = null;
if (currentServiceName != null)
{
service = currentServiceName.Replace(" ", "");
}
NewNotePanel newNote = new NewNotePanel(e.FullPath, service, listOfService, Path, MyConn, ipAddress, imgFolder, Utente_id);
newNote.TopMost = true;
watcher.EnableRaisingEvents = false;
var result = newNote.ShowDialog();
if(result == DialogResult.OK || result == DialogResult.Cancel)
{
watcher.EnableRaisingEvents = true;
if(result == DialogResult.OK)
{
this.BeginInvoke(new InvokeDelegate(Refresh));
}
}
loop = 0;
}
else
{
loop++;
}
}
这是Refresh()函数:
public void Refresh()
{
noteContainer.Controls.Clear();
page = 0;
try
{
string Query = "SELECT a, v, b, cFROM note Where Servizio_ID = " + asd+ " AND Visibile = 1 order by ID desc limit 15 OFFSET " + (pageIndex * page) + " ;";
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MySqlDataReader MyReader;
if (MyConn.State == ConnectionState.Open)
{
MyReader = MyCommand.ExecuteReader();// Here our query will be executed and data saved into the database.
while (MyReader.Read())
{
CreateNotePreview(MyReader.GetString("a"), MyReader.GetString("b"), MyReader.GetString("c"), MyReader.GetString("d"));
}
MyReader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
由于在触发FileSystemWatcher的“Change”事件时调用了OpenFormNewNote ...当然它在一个独立的线程上运行。而不是Refresh()做一些UI的东西,它不能直接从OpenFormNewNote()调用,否则它给出一个跨线程异常。所以我尝试使用委托,但是当代码流到达BeginInvoke部分时..没有任何反应,并且不会调用Refresh函数。
我该怎么办?