日期:2014-05-17  浏览次数:20822 次

为什么异步调用方法中的线程与窗体线程一样?
在异步处理中,如果调用异步方法时,会在线程池调一个新的线程,
但在这里的调用异步方法中,得到的线程与窗体是同一个线程,为什么呀?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ASY
{
    public partial class Form1 : Form
    {
        public delegate void delegateInvoke();

        public Form1()
        {
            InitializeComponent();
            int threadid = AppDomain.GetCurrentThreadId();
            MessageBox.Show("Main thread is "+ threadid.ToString());
        }

        public void InvokedMethod()
        {
            int threadid = AppDomain.GetCurrentThreadId();
            //与窗体是同一个线程
            MessageBox.Show("Sub thread is " + threadid.ToString());
            textBox1.Text = "New thread"; 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            delegateInvoke delegateinvoke = new delegateInvoke(InvokedMethod);
            IAsyncResult ir = textBox1.BeginInvoke(delegateinvoke);
        }
    }
}

------解决方案--------------------
引用:
在异步处理中,如果调用异步方法时,会在线程池调一个新的线程,
但在这里的调用异步方法中,得到的线程与窗体是同一个线程,为什么呀?

虽然没写过winform的程序 但是应该都差不多
楼主的这个程序肯定是由问题的
ui对象应该只能被主线程调用
其他线程调用会直接抛错
楼主这个直接在其他线程里面操作ui对象 很定不是另起的后台线程
一般我们用delegate的BeginInvoke方法创建新的线程
而你用ui对象的textBox1.BeginInvoke创建的 我不知道是否是后台线程
从现象上看是主线程
所以会出现你的现象
------解决方案--------------------
 private void button1_Click(object sender, EventArgs e)
        {
            Action action=InvokedMethod;
action.BeginInvoke...
        }

这样直接异步了 多简单呢  呵呵