UI unresponsive until action is complete

前端 未结 2 765
一个人的身影
一个人的身影 2021-01-03 16:25

I\'m not sure if the Title is a good description of this issue or not. Essentially what I have is a WinForm app that retrieves a list of files from a folder into a ListView,

相关标签:
2条回答
  • 2021-01-03 17:06

    You could offload the long-running operation to a ThreadPool thread, by using async/await and the handy Task.Run method:

    transferResult = await Task.Run(() => session.PutFiles(readyFile, destFile, false, transferOptions));
    

    ...and:

    transferResult = await Task.Run(() => session.PutFiles(triggerFile, destFile, false, transferOptions));
    

    You should also add the async modifier in the event handler, in order to enable the await operator.

    Important: Avoid doing anything UI related in the offloaded method. If you want to communicate with the UI during the operation, for example for progress reporting, use the Progress<T> class.

    0 讨论(0)
  • 2021-01-03 17:14

    You cannot do lengthy operations on the GUI thread. Do them on a background thread.

    The answer by @Theodor correctly shows that you can move the PutFiles to the thread pool.

    Another option is to move all your upload logic to the thread pool and call back to the main thread using Control.Invoke for GUI updates only.

    For a full example, see WinSCP article Displaying FTP/SFTP transfer progress on WinForms ProgressBar.

    Pick the option that suits you better. I believe that my approach is easier to grasp for someone unexperienced with thread programming.

    0 讨论(0)
提交回复
热议问题