您的位置:程序门 -> .net技术 -> c#



vs.net2005中,c#如何用多线程访问用户界面控件?


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


vs.net2005中,c#如何用多线程访问用户界面控件?
发表于:2007-02-14 11:35:54 楼主
本人做了一个窗体,窗体上有许多控件(例如:listbox,progress),点击某个按钮,开启一个线程,在线程中如何访问listbox,progress等控件,通过代码能够方便控制这个界面控件,vs.net2003上可以直接访问,vs.net2005上怎么处理,请高手多多指点,急用,谢谢!
发表于:2007-02-14 11:41:001楼 得分:0
invoke,   begininvoke

楼主去msdn查一下这两个函数把
发表于:2007-02-14 11:42:522楼 得分:0
2003   2005都不能直接访问的.
查查   begininvoke
发表于:2007-02-14 13:11:103楼 得分:0
up
发表于:2007-02-14 13:51:394楼 得分:0
你可以尝试一下backgroundworker这个控件。2005新的一个关于多线程的东东。比较好用。可以参考一下msdn。
//---------------------------------------------------------------------
//     this   file   is   part   of   the   microsoft   .net   framework   sdk   code   samples.
//  
//     copyright   (c)   microsoft   corporation.     all   rights   reserved.
//  
//this   source   code   is   intended   only   as   a   supplement   to   microsoft
//development   tools   and/or   on-line   documentation.     see   these   other
//materials   for   detailed   information   regarding   microsoft   code   samples.
//  
//this   code   and   information   are   provided   as   is   without   warranty   of   any
//kind,   either   expressed   or   implied,   including   but   not   limited   to   the
//implied   warranties   of   merchantability   and/or   fitness   for   a
//particular   purpose.
//---------------------------------------------------------------------
#region   using   directives

using   system;
using   system.collections.generic;
using   system.componentmodel;
using   system.data;
using   system.drawing;
using   system.text;
using   system.windows.forms;

#endregion

namespace   microsoft.samples.windows.forms.eventbasedasync
{

        //   note:   in   order   to   support   cancellation   and   progress   reporting   the   following
        //               properties   have   been   set   to   true   on   backgroundworker1
        //  
        //                       this.backgroundworker1.workerreportsprogress   =   true;
        //                       this.backgroundworker1.workersupportscancellation   =   true;
        //  

        partial   class   simplebackgroundworkerform   :   form   {
                public   simplebackgroundworkerform()   {
                        initializecomponent();
                }

                ///   <summary>
                ///   handle   the   form   load   event
                ///   sets   the   default   value   of   the   masked   text   box
                ///   </summary>
                private   void   simplebackgroundworkerform_load(system.object   sender,   system.eventargs   e)   {
                        this.mtxtinput.text   =   "2 ";
                }

                ///   <summary>
                ///   handle   the   click   event   on   btnstart.  
                ///   start   the   background   worker   task   passing   mtxtinput   as   the   input   to   the   task
                ///   via   runworkerasync
                ///   </summary>
                private   void   btnstart_click(system.object   sender,   system.eventargs   e)   {
                        btncancel.enabled   =   true;
                        btnstart.enabled   =   false;
                        operationtoolstripprogressbar.value   =   0;
                        operationtoolstripprogressbar.visible   =   true;
                        operationtoolstriptextprogresspanel.text   =   "calculating   result ";

try
{
int   inputnumber   =   int32.parse(this.mtxtinput.text);
backgroundworker1.runworkerasync(inputnumber);
}
catch   (formatexception   mye)
{
                                messagebox.show( "you   must   enter   only   integers   in   the   maskedtextbox "   +   mye.message.tostring(),   "async   backgroundworker   sample ");
btnstart.enabled   =   true;
}
                }

                ///   <summary>
                ///   handle   the   click   event   on   btncancel.
                ///   cancel   the   background   worker   task
                ///  
                ///   note:   it   is   possible   that   the   task   may   have   completed   by   the   time   cancel   is   processed
                ///               -   you   will   need   to   take   this   into   account   in   your   applications
                ///  
                ///   note:   this   is   only   supported   if  
                ///  
                ///               (1)   you   set   workersupportscancellation   =   true  
                ///               (2)   you   respond   to   cancellationpending   in   the   dowork   event   (see   below)
                ///  
                ///   </summary>
                private   void   btncancel_click(system.object   sender,   system.eventargs   e)   {
                        backgroundworker1.cancelasync();
                }

                ///   <summary>
                ///   handle   the   dowork   event   on   the   backgroundworker.
                ///  
                ///   note   well:   this   event   runs   on   a   seperate   thread   not   on   the   ui   thread
                ///                         you   put   your   long   running   task   in   this   event   handler   and   it   is  
                ///                         invoked   via   runworkerasync.
                ///  
                ///   as   this   event   runs   on   a   background   thread   you   should   not   directly   access
                ///   controls   in   this   event.
                ///  
                ///   you   can   call   reportprogress   to   raise   the   progress   event   on   the   ui   thread  
                ///   you   can   set   the   result   which   is   returned   to   the   ui   thread   in   the   completed   event  
                ///   you   can   use   control.invoke/control.begininvoke   to   set   the   state   of   controls   on   the   ui   thread
                ///  
                ///   when   this   event   handler   exits   the   completed   event   is   raised   on   the   ui   thread
                ///  
                ///   </summary>
                private   void   backgroundworker1_dowork(system.object   sender,   system.componentmodel.doworkeventargs   e)   {
//   this   method   will   run   on   a   thread   other   than   the   ui   thread.
//   be   sure   not   to   manipulate   any   windows   forms   controls   created
//   on   the   ui   thread   from   this   method.

                //get   the   input   argument   from   the   event   args
int   inputnumber   =   convert.toint32(e.argument);

                //throw   an   exception   if   input   is   greater   than   1000
                //this   causes   the   completed   event   to   be   raised   with   e.error   containing
                //this   exception
                if   (inputnumber   >   1000)  
throw   new   argumentexception( "we   only   support   numbers   up   to   1000 ");

                //do   the   operation   -   simply   double   the   number
int   result   =   inputnumber   *   2;

                //now   simulate   a   long   running   task   by   looping   for   2000   milliseconds
                //if   cancelasync   is   called   cancellationpending   is   true.   look   for   this   and  
                //terminate   the   task   if   cancellationpending   is   true
int   i   =   1;
                while   (i   <   100   &&     !backgroundworker1.cancellationpending)
{

                        //sleep   for   5   milliseconds
                        system.threading.thread.sleep(20);

                        //report   progress   back   to   the   ui   thread   via   reportprogress
                        backgroundworker1.reportprogress(i);

                        i   +=   1;
}

                //if   the   user   canceled   the   task   then   set   e.cancel   to   true
                //so   that   in   the   completed   we   can   detect   that   the   cancellation
                //suceeded
                if   (backgroundworker1.cancellationpending)  
                        e.cancel   =   true;

                //set   the   result   into   the   event   args   to   be   picked   up   by   completed   event
e.result   =   result;

}

发表于:2007-02-14 13:51:445楼 得分:0
///   <summary>
                ///   handle   the   loadcompleted   event.   this   event   is   raised   when   the   backgroundworker   dowork   event  
                ///   handler   has   finished   EXECuting
                ///   the   runworkercompletedeventargs   contains   information   about   the   task
                ///   -   the   result,   whether   it   was   canceled,   if   there   was   an   error   and   so   on
                ///   </summary>
                private   void   backgroundworker1_runworkercompleted(object   sender,   system.componentmodel.runworkercompletedeventargs   e)   {
                        btncancel.enabled   =   false;
                        btnstart.enabled   =   true;
                        operationtoolstripprogressbar.value   =   0;  
                        operationtoolstripprogressbar.visible   =   false;
                        operationtoolstriptextprogresspanel.text   =   "ready ";

                        if   (e.cancelled   ==   true)   {
                                messagebox.show( "background   task   canceled ",   "async   backgroundworker   sample ");
                        }   else   {

                                //
                                //note:   if   the   web   service   returned   an   error   e.result   will   throw   the   exception   associated   with   the   error
                                //
                                //             you   can   also   check   for   e.error:
                                //
                                //                       if   (e.error   !=   null)   {
                                //                       }
                                //
try
{
txtoutput.text   =   e.result.tostring();
                                        messagebox.show( "background   task   completed ",   "async   backgroundworker   sample ");
}
catch   (exception   ex)
{
                                        messagebox.show(ex.message,   "async   backgroundworker   sample ",   messageboxbuttons.ok,   messageboxicon.exclamation);
}
                        }
                }

                ///   <summary>
                ///   handle   the   progresschanged   event.   this   event   is   raised   during   the   EXECution   of  
                ///   dowork   is   reportprogress   is   called.   it   can   be   used   to   give   progress   feedback   to   the  
                ///   user.
                ///  
                ///   the   progresschangedeventargs   contains   the   percentage   complete   as   reported   by   reportprogress.
                ///  
                ///   note:   this   is   only   supported   if   you   set   workerreportsprogress   =   true  
                ///  
                ///   </summary>
                private   void   backgroundworker1_progresschanged(object   sender,   system.componentmodel.progresschangedeventargs   e)   {
                        operationtoolstripprogressbar.value   =   e.progresspercentage;
                }

        }
}

发表于:2007-02-14 15:11:026楼 得分:0
有没有关于invoke,   begininvoke的例子?
发表于:2007-03-04 11:25:077楼 得分:0
我一般都是用委托实现的:
using   system;
using   system.collections.generic;
using   system.componentmodel;
using   system.data;
using   system.drawing;
using   system.text;
using   system.windows.forms;
using   system.threading;

namespace   smartclientcaculator
{
        public   partial   class   form1   :   form
        {
                private   caculatorcomponent.caculator   cal   ;
                public   form1()
                {
                        initializecomponent();
                }
                void   longwork()
                {
                        cal.longwork();
                        listbox1.invoke(new   testdelegate(listbox1.items.insert),   new   object[]   {   0,   "info "   });
                        textbox3.invoke(new   settext(showtextinfo),   new   object[]   {   "信息! "});
                }

                private   void   button1_click(object   sender,   eventargs   e)
                {
                        //do();
                        //button1.begininvoke(new   doworkdelegate(do),   null);
                        //thread   thread   =   new   thread(new   threadstart(do));

                        thread   thread   =   new   thread(new   threadstart(longwork));

                        thread.start();

                        //for   (int   i   =   0;   i   <   10000;   i++)
                        //{
                        //         listbox1.invoke(new   testdelegate(listbox1.items.insert),   new   object[]   {   0,   "info "   });
                        //}
                }

        }
}


快速检索

最新资讯
热门点击