WinForm Application UI Hangs during Long-Running Operation

前端 未结 3 1511
梦毁少年i
梦毁少年i 2020-11-22 05:13

I have a windows forms application on which I need to use a for loop having a large number of Remote Calls around 2000 - 3000 calls,

and while executing the for loop

相关标签:
3条回答
  • 2020-11-22 05:23

    Obviously, you need to use background threads. I suggest you read this free e-book.

    0 讨论(0)
  • 2020-11-22 05:31
        private voidForm_Load(object sender, EventArgs e)
        {
            MethodInvoker mk = delegate
            {
                //your job
            };
            mk.BeginInvoke(callbackfunction, null);
        }
    
        private void callbackfunction(IAsyncResult res)
        {
            // it will be called when your job finishes.
        }
    

    use MethodInvoker is the easiest way.

    0 讨论(0)
  • 2020-11-22 05:37

    You need to perform the long running operation on a background thread.

    There are several ways of doing this.

    1. You can queue the method call for execution on a thread pool thread (See here):

      ThreadPool.QueueUserWorkItem(new WaitCallback(YourMethod));
      

      In .NET 4.0 you can use the TaskFactory:

      Task.Factory.StartNew(() => YourMethod());
      

      And in .NET 4.5 and later, you can (and should, rather than TaskFactory.StartNew()) use Task.Run():

      Task.Run(() => YourMethod());
      
    2. You could use a BackgroundWorker for more control over the method if you need things like progress updates or notification when it is finished. Drag the a BackgroundWorker control onto your form and attach your method to the dowork event. Then just start the worker when you want to run your method. You can of course create the BackgroundWorker manually from code, just remember that it needs disposing of when you are finished.

    3. Create a totally new thread for your work to happen on. This is the most complex and isn't necessary unless you need really fine grained control over the thread. See the MSDN page on the Thread class if you want to learn about this.

    Remember that with anything threaded, you cannot update the GUI, or change any GUI controls from a background thread. If you want to do anything on the GUI you have to use Invoke (and InvokeRequired) to trigger the method back on the GUI thread. See here.

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