C# in Async Task change Label Text

前端 未结 5 718
清酒与你
清酒与你 2021-01-03 09:50

The following Code does not change the Text and stops executing the Task

private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = \         


        
5条回答
  •  清酒与你
    2021-01-03 10:44

    I think both the questions and some of the answers are not clear. Depending on where in the task thread you need to update the label you have to use invoke. Otherwise you can leverage await and leverage the standard semantics.

        private async void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Starting to run a long task... carry on...";
            await snooze(3);
            label1.Text = "Done with long task";
        }
    
        public Task snooze(int seconds)
        {
            label1.Text = "zzzz...";
            return Task.Run(
            () => {
                label1.Invoke(new Action(() => label1.Text = "For some reason I need to alert you here.. bad dream perhaps...direct access to label1 will fail"));
                Thread.Sleep(seconds * 1000);
                return  seconds;
               });
    
        }
    

提交回复
热议问题