C#背景工作者基础 - 这是合法的

时间:2014-06-12 17:57:40

标签: c# multithreading backgroundworker

我想知道这是否是使用后台工作线程的合法方式。

基本上我正在编写一个使用GPS加密狗来捕捉当前位置的应用。加密狗以1秒的间隔将数据写入串口。

我的第一次尝试是

namespace _10Task__not_working_background
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static int count = 0;

        public MainWindow()
        {
            InitializeComponent();

            var incrementCount = Task.Factory.StartNew(() => { 
                while(true)
                {
                    Thread.Sleep(1000);
                    count++;
                }
            });

            var ReadCount = Task.Factory.StartNew(() => { 
                while(true)
                {
                    Thread.Sleep(1000);
                    //poll_tb is a textblock on my wpf form
                    Poll_TB.Text = count.ToString();
                }
            });
        }
    }
}

导致以下异常

  

{&#34;调用线程无法访问此对象,因为它不同   线程拥有它。&#34;}

我回想起有关wpf表单和额外线程的一些事情,无论如何,我最终使用aBackgroundWorker来更新我的计数器。

namespace _09Task___backgroundwithUI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static int count = 0;
        private BackgroundWorker worker;

        public MainWindow()
        {
            InitializeComponent();

            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;

            worker.DoWork += IncrimentCount;
            worker.ProgressChanged +=worker_ProgressChanged;

            if (!worker.IsBusy)
                worker.RunWorkerAsync();
        }

        private void IncrimentCount(object sender, DoWorkEventArgs e)
        {
            var bw = sender as BackgroundWorker;

            var t = Task.Factory.StartNew(() =>
            {
                while (!e.Cancel)
                {
                    Thread.Sleep(1000);
                    count++;
                    bw.ReportProgress(50);
                }
            });

           Task.WaitAll(t);
        }

        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //CountPoll_TBis a textblock on my wpf form
            CountPoll_TB.Text = count.ToString();
        }
    }
}

这有意义还是我离开这里?

0 个答案:

没有答案