线程异步调用

Thread objThread = new Thread(new ThreadStart(delegate
            {
                Dispatcher.BeginInvoke(new Action(() =>--解决调用线程必须为 STA,因为许多 UI 组件都需要的问题
                {
                    ReportViewer rp = ReportingServiceHelper.GetReportView(reportName, null, true, true);
                    rp.RefreshReport();
                    CurrentView = ReportingServiceHelper.GetFormHost<ReportViewer>(rp);
                }));

            }));
            objThread.Start();

 

http://blog.csdn.net/yl2isoft/article/details/11711833

 http://www.cnblogs.com/nokiaguy/archive/2008/07/13/1241817.html

http://blog.csdn.net/razorluo/article/details/7814670

 

http://www.111cn.net/net/160/42786.htm

http://www.sufeinet.com/thread-3707-1-1.html

 

调用控件的BeginInvoke实现异步

/// <summary>
         /// 线程调用BeginInvoke
         /// </summary>
         private void ThreadBeginInvoke()
         {
             listBox1.Items.Add("--begin--");
             new Thread(() =>
             {
                 Thread.CurrentThread.Name = "ThreadBeginInvoke";
                 Thread.Sleep(10000);
                 string temp = "Before!";
                 listBox1.BeginInvoke(new Action(() =>
                 {
                     this.listBox1.Items.Add(temp + ":" + Thread.CurrentThread.Name);
                 }));
                 temp += "After!";
             }).Start();
             Thread.Sleep(1000);
             listBox1.Items.Add("--end--");
         }

 

委托实现异步

  public delegate int AddOp(int x, int y);

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("******* 委托异步线程 两个线程“同时”工作 *********");

            //显示主线程的唯一标示

            Console.WriteLine("调用Main()的主线程的线程ID是:{0}.", Thread.CurrentThread.ManagedThreadId);

            //将委托实例指向Add()方法

            AddOp pAddOp = new AddOp(Add);

            //开始委托次线程调用。委托BeginInvoke()方法返回的类型是IAsyncResult,

            //包含这委托指向方法结束返回的值,同时也是EndInvoke()方法参数

            IAsyncResult iftAR = pAddOp.BeginInvoke(10, 10, null, null);

            Console.WriteLine(""nMain()方法中执行其他任务........"n");

            int sum = pAddOp.EndInvoke(iftAR);

            Console.WriteLine("10 + 10 = {0}.", sum);

            Console.ReadLine();

        }

        //求和方法

        static int Add(int x, int y)

        {

            //指示调用该方法的线程ID,ManagedThreadId是线程的唯一标示

            Console.WriteLine("调用求和方法 Add()的线程ID是: {0}.", Thread.CurrentThread.ManagedThreadId);

            //模拟一个过程,停留5秒

            Thread.Sleep(5000);

            int sum = x + y;

            return sum;

        }

    }

}

 

 

 

 

posted on 2014-03-26 15:54  swarb  阅读(143)  评论(0编辑  收藏  举报