前言: WPF中按鈕點擊事件如何執行時間太長會導致整個UI線程卡頓,現象就是頁面刷新卡住,點擊其他按鈕無反饋。如下是進行異步執行命令,并遠程上傳文件的代碼。
{SystemModel device = SystemModel.GetGlobalInstance();int robotindex = device.SelectedRobotIndex;string selectRobotIp;string temp;if (!Directory.Exists(hostFilePath)){temp = "相機本地配置文件夾不存在,請檢查!";Growl.Error(temp, _token);return;}if (!device.robotIdToIpDict.TryGetValue(robotindex, out selectRobotIp)){temp = "Robot " + (robotindex + 1) + " not connected yet, load faliure!";Growl.Error(temp, _token);return;}Task<bool> task = Task.Run(() => ExecuteLongProcedure(this, selectRobotIp, remoteFilePath, hostFilePath, userName, passWord));await Task.WhenAll(task);bool result = task.Result;if (result){device.LoadCameraConfigFlag = true;temp = "相機配置文件加載成功!";Growl.Success(temp, _token);} else {temp = "相機配置文件傳輸失敗!";Growl.Error(temp, _token);}}private bool ExecuteLongProcedure(object context, string selectRobotIp, string remoteFolderPath, string hostFolderPath, string userName, string passWord){bool transferFlag = true;string temp;string[] filePaths = Directory.GetFiles(hostFolderPath);foreach (string filepath in filePaths){string filename = Path.GetFileName(filepath);// 網絡攝像頭分組A的配置文件均進行發送if (!filename.EndsWith("Group0.config")){continue;}string remoteFilePath = $"{remoteFolderPath}/{filename}";using (var client = new SftpClient(selectRobotIp, userName, passWord)){try{client.BufferSize = 1024;client.Connect();using (var fileStream = new FileStream(filepath, FileMode.Open)){client.UploadFile(fileStream, remoteFilePath);}}catch (Exception ex){transferFlag = false;temp = filename + $"文件傳輸失敗:{ex.Message}";Growl.Warning(temp, _token);return false;}finally{if (client.IsConnected){client.Dispose();// 此處斷連后一定sleep一會兒再重新連接,否則會提示超時Thread.Sleep(200);}}}}return transferFlag;}