我在我的 wpf 应用程序中使用 BackgroundWorker 进行线程处理。但这会使 UI 挂起,因为我无法单击 UI 的任何位置。这是我的代码片段:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
Dispatcher.Invoke(new Action(() => ConnectFtp()));
};
worker.RunWorkerAsync();
}
private void ConnectFtp()
{
try
{
int port = string.IsNullOrEmpty(txtport.Text) ? 21 : Convert.ToInt32(txtport.Text);
if (ftpserver1 == null)
{
ftpserver1 = new FtpClient(txtftpserver.Text, port);
ftpserver1.ServerResponse += new EventHandler<FtpResponseEventArgs>(ftpserver2_ServerResponse);
ftpserver1.ClientRequest += new EventHandler<FtpRequestEventArgs>(ftpserver2_ClientRequest);
ftpserver1.TransferProgress += new EventHandler<TransferProgressEventArgs>(ftpserver2_TransferProgress);
ftpserver1.TransferComplete += new EventHandler<TransferCompleteEventArgs>(ftpserver2_TransferComplete);
}
if (!ftpserver1.IsConnected)
{
Run r = new Run("Server1 Status: Resolving address of " + txtftpserver.Text + "\n" + "Server1 Status: Connection established, waiting for welcome message... \n");
r.Foreground = System.Windows.Media.Brushes.Black;
msg.Inlines.Add(r);
msgscroll.ScrollToBottom();
ftpserver2_OpenAsyncCompleted(ftpserver1, txtusername.Text, txtpassword.Password);
}
}
catch { }
}
在 ConnectFtp() 方法中,我连接到 ftp 服务器。当 ftp 服务器的连接状态为“正在连接”时,UI 不起作用。但完成连接后一切正常!请帮帮我!提前致谢!