从不同的线程更新UI

时间:2016-06-04 11:34:34

标签: c# multithreading task marshalling

这是我的第一个问题。由于英语不是我的第一语言,请原谅我的任何错误。

我正在尝试开发Windows Phone 8.1(XAML和C#)的应用程序,并且我正在使用.NET Framework 4.5.2。 我刚刚开始在C#中学习多线程,如果有人在这里帮助我,我将不胜感激。到目前为止,我发现的相关问题的所有答案都过于复杂。

我只需要通过按钮点击创建一个新任务,在文本块控件中显示一条消息。

private void myButton_Click(object sender, RoutedEventArgs e)
{
    Task t = new Task(MyMethod);
    t.Start();
}

private void MyMethod()
{
    myTextBlock.Text = "Worked!";
}

我收到以下异常:应用程序调用了为不同线程编组的接口。 (来自HRESULT的异常:0x8001010E(RPC_E_WRONG_THREAD))。

我该如何纠正?

提前致谢!

3 个答案:

答案 0 :(得分:1)

如果你使用async / await编程模型,你可以很容易地做到这一点。

而不是你拥有的,尝试这样的事情:

private async void myButton_Click(object sender, RoutedEventArgs e)
{
    Task t = MyMethod();
    await t;
}

private async Task MyMethod()
{
    myTextBlock.Text = "Worked!";
}

答案 1 :(得分:0)

设计师代码:

namespace Tasks
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(41, 43);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(131, 43);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 1;
            this.button2.Text = "button2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(41, 84);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(165, 20);
            this.textBox1.TabIndex = 2;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(240, 151);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.TextBox textBox1;
    }
}

这是表格代码:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tasks
{
    public partial class Form1 : Form
    {
        //Just incase you need to stop the current task
        CancellationTokenSource cts;

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //showing that the form is still working
            MessageBox.Show(this,"This button still works :)");
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            cts = new CancellationTokenSource();

            await CreateTask();
        }

        private async Task CreateTask()
        {
            //Create a progress object that can be used within the task
            Progress<string> mProgress; //you can set this to Int for ProgressBar
            //Set the Action to a function that will catch the progress sent within the task
            Action<string> progressTarget = ReportProgress;
            //Your new Progress with the included action function
            mProgress = new Progress<string>(progressTarget); 

            //start your task
            string result = await MyProcess(mProgress);

            MessageBox.Show(this, result);
        }

        //notice the myProgress this can be used within your task to report back to UI thread.
        private Task<string> MyProcess(IProgress<string> myProgress)
        {
            return Task.Run(() =>
            {
                //here you will sen out to your UI thread whatever text you want.
                //typically used for progress bar.
                myProgress.Report("It Works..");
                //your tasks return
                return "Yes it really does work...";

            }, cts.Token);
        }

        private void ReportProgress(string message)
        {
            //typically to update a progress bar or whatever
            //this is where you Update your UI thread with text from within the Task.
            textBox1.Text = message;
        }
    }
}

基本上你正在做的是传递一个可用于你的任务的进度。

答案 2 :(得分:0)

如果您在Windows Phone(WinRT,而不是Silverlight)项目中,您也可以使用

ws.Cells[1, 1] = @"Folder names";
for(int row = 2; row <= count; row ++)
{
    var name = Namelist[row-2];
    ws.Cells[1, row] = name;
}