컴파일 파일로 실행하면 잘 되는데 디버깅으로 실행하면 TargetInvocationException 떨어짐


"크로스 스레드 작업이 잘못되었습니다. 'tbxResult' 컨트롤이 자신이 만들어진 스레드가 아닌 스레드에서 액세스되었습니다."



소스 

-----

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

using System.Windows.Forms;


namespace AsyncAwait

{

    public partial class Form1 : Form

    {

        private CancellationTokenSource cancelTokenSrc;

        public Form1()

        {

            InitializeComponent();      

        }


        private void btnStart_Click(object sender, EventArgs e)

        {

            lblState.Text = "계산중...";

            Calc();

        }



        async void Calc()

        {

            cancelTokenSrc = new CancellationTokenSource();

            CancellationToken token = cancelTokenSrc.Token;


            Task<int> task = Task.Factory.StartNew<int>(() =>

            {

                int sum = 0;


                for (int i = 0; i < 100; i++)

                {

                    tbxResult.Text = i.ToString();


                    if (cancelTokenSrc.Token.IsCancellationRequested)

                    {

                        progBar.Value = 0;

                        progBar.Enabled = false;

                        return 0;

                    }

                    sum += i;


                    Thread.Sleep(1000);

                }

                return sum;

            }, token);


            dynamic res = await task;


            if (res != 0)

            {                

                lblState.Text = "작업 완료";

            }

            else

            {

                tbxResult.Text = "";

                lblState.Text = "작업 취소";

            }

        }


        private void btnCancel_Click(object sender, EventArgs e)

        {

            cancelTokenSrc.Cancel();

        }


        private void Form1_Load(object sender, EventArgs e)

        {

            progBar.Style = ProgressBarStyle.Blocks;

            progBar.Minimum = 0;

            progBar.Maximum = 100;

            progBar.Step = 1;

            progBar.Value = 0;


            progBar.Enabled = true;

        }

    }

}


-----