C# update and append textbox value using backgroundworker process

后端 未结 5 1271
心在旅途
心在旅途 2020-12-31 05:09

I\'ve got a c# windows form app I threw together. It\'s fairly simple:\\

inputs:

  • text string
  • source folder path
  • destination folder
5条回答
  •  醉话见心
    2020-12-31 05:54

    The UI doesn't update because you're not allowing any window messages to be processed in your long-running file processing loop. WinForms apps redraw in response to WM_PAINT messages which are processed in the message queue in the main thread.

    The simplest solution is to force a UI update: Try calling Update() on your form after modifying the textbox inside your loop.

    Your app will still be UI frozen (non responsive to mouse clicks, etc) but this should at least get the progress messages drawn on the screen. If updating the display is all you really need, then stop here.

    The next level of solution would be to allow your application to process pending window messages in your file processing loop. Call Application.DoEvents() in your loop (Instead of form.Update). This will allow the form to redraw itself with your text output updates and will eliminate your UI freeze - the app can respond to mouse and keyboard activity.

    Be careful here, though - the user could click the button that started the current activity while the current activity is in progress - reentrancy. You should at a minimum disable the menu or button that kicks off your long-running file processing to prevent reentrancy.

    A third level of solution would be to use a background thread for the file processing. This introduces a whole host of new issues you need to be aware of, and in many cases threads are overkill. There's not much point in pushing the file processing off into a background thread if you're not going to allow the user to do anything else with your app while the file processing is happening.

提交回复
热议问题