Execute simple Logic without “locking” the UI

后端 未结 4 1173
一个人的身影
一个人的身影 2021-01-26 05:41

I have a dialog with some txb\'s and a button. When this button is clicked I want to change the button\'s Text, disable the button, start some Logic and then close the Window.

相关标签:
4条回答
  • 2021-01-26 05:58

    You could use a backgroundworker:

    BackgroundWorker worker = new BackgroundWorker();
    worker.WorkerSupportsCancellation = false;
    worker.WorkerReportsProgress = false;
    
    worker.DoWork += (s, e) =>
        {
            //perform action
        };
    
    worker.RunWorkerCompleted += (s, e) =>
        {
            //close window
        };
    
    worker.RunWorkerAsync();
    

    See this for more details.

    0 讨论(0)
  • 2021-01-26 06:05

    You can have a thread that performs the calculation. This may help: Threads in CSharp

    0 讨论(0)
  • 2021-01-26 06:16

    Here's what I would do:

    private async void ButtonClick() 
    {
        //here, you're on the UI Thread
        button1.Enabled = false;
    
        await Task.Run(() => DoTheWork());
    
        //you're back on the UI Thread
        button1.Enabled = true;
    }
    
    private void DoTheWork() 
    {
        //this will be executed on a different Thread
    }
    
    0 讨论(0)
  • 2021-01-26 06:16

    when button is clicked:

    button.Enabled = false;
    button.Text = "new text";
    Task.Factory.StartNew(() =>
    {
        // do your tasks here and close the window.
        // type your code normally like calling methods. setting variables etc...
    
        StaticVariable = ExampleUsingMethod();
    });
    

    if your variable needs to be assigned to UI later then you need dispatcher.for example if you want to change button inside the new thread.

    Task.Factory.StartNew(() =>
    {
           Dispatcher.Invoke(() => 
           {
              button.Enabled = false;
              button.Text = "new text";
           }
    
           StaticVariable = ExampleUsingMethod();
    });
    
    0 讨论(0)
提交回复
热议问题