Using thread in Silverlight is a problem that is easily ignored.

Source: Internet
Author: User

There is a very common function. We need to regularly call the service in a subwindow, and then update the control content. As long as the window is open, the service will always be called.

Now let's complete this function. First define a service:

 
Public ClassService1: iservice1 {Public StringDowork (StringName) {file. appendalltext (path. Combine (appdomain. currentdomain. basedirectory,"Log.txt"),String. Format ("Time: {0} thread: {1 }"+ Environment. newline, datetime. Now, name ));Return "OK";}}

Before returning data, this service will write a local text log, the write time and input parameters.

Add a subwindow and place a button on the page to open the window:

 
Childwindow1 c =NewChildwindow1 (); C. Show ();

SubwindowCodeAs follows:

     Public   Partial   Class Childwindow1: childwindow { Private Thread thread; Private   Static   Int Threadnum = 0; Private Servicereference1.service1client S = New Servicereference1.service1client (); Public Childwindow1 () {initializecomponent (); S. doworkcompleted + = New Eventhandler <servicereference1.doworkcompletedeventargs> (s_doworkcompleted );} Private   Void S_doworkcompleted ( Object Sender, servicereference1.doworkcompletedeventargs e) {dispatcher. begininvoke () => message. Items. insert (0, String . Format ( "Service Return: {0} Control: {1} Time: {2} thread: {3 }" , E. Result, message. gethashcode (), datetime. Now, E. userstate. tostring ())));} Private   Void Childwindow_loaded ( Object Sender, routedeventargs e) {interlocked. increment (Ref Threadnum); thread = New Thread (State => {var threadid = ( Int ) State; While ( True ) {S. doworkasync (threadid. tostring (), threadid); thread. Sleep (1000) ;}); thread. Start (threadnum );}

This code is simple:

1. We have a static variable that saves the total number of threads.

2. Open + 1 in each window

3. initialize a thread each time the window is opened. The thread is used to continuously call the service and then sleep for 1 second. The input parameter during the call is the current thread number (starting from 1)

4. After the service is called, we will update the ListBox on the page and add a piece of data, including the service return value, message control identifier, current time, and background thread number.

Okay, the function is complete, runProgram, We expect that after opening the sub-window:

1. a row of records is inserted in the ListBox of the subwindow every second.

2. The server writes a line of records to the text file every second.

3. The thread numbers of the two are consistent, and each time the sub-window opens, the thread numbers will be + 1

 

Run the program and open the subwindow:

Check the log on the server:

It seems that our requirements have been fulfilled. Is this program really okay?

The second sub-window is opened:

No problem, but the log on the server is incorrect (it does not mean that there is no problem ):

This indicates that the two backend threads are running at the same time. We cannot take it for granted that the subwindow is closed, and the old thread will end (it may feel that it is not a static field anyway, when the window is closed, wait for it to recycle the thread ).

Silverlight programs rarely refresh pages. As more sub-window switches and threads increase, the previous threads always call services.

As the Sub-window is switched for countless times, there are countless threads in the background calling the server. It is also terrible to think about it!

There is no problem with front-end display (why is there no more display in ListBox? You can think about it), which may increase the pressure on the server. We hope that the background thread can end after the sub-window is closed.

Many may write this:

Private VoidChildwindow_closed (ObjectSender, eventargs e ){If(Thread! =Null){Try{Thread. Abort ();}Catch{}}}

End the thread when the sub-window is closed. It will throw threadabortexception.

Switch the sub-window several times to see:

Or is the thread not finished?

Take it for granted! In fact, why force end the thread? Let the thread finish it on its own:

This is normal. Of course, you can also use backgroundworker to implement this function:

 Using System; Using System. Collections. Generic;Using System. LINQ; Using System. net; Using System. windows; Using System. Windows. controls; Using System. Windows. documents; Using System. Windows. input; Using System. Windows. Media; Using System. Windows. Media. animation; Using System. Windows. shapes; Using System. Threading; Using System. componentmodel; Namespace Silverlightapplication2 {Public   Partial   Class Childwindow1: childwindow { Private   Static   Int Threadnum = 0; Private Servicereference1.service1client S = New Servicereference1.service1client (); Private Backgroundworker BW = New Backgroundworker (); Public Childwindow1 () {initializecomponent (); S. doworkcompleted + = New Eventhandler <servicereference1.doworkcompletedeventargs> (s_doworkcompleted); BW. workersuppscanscancellation = True ; BW. workerreportsprogress = True ; BW. dowork + = New Doworkeventhandler (bw_dowork); BW. progresschanged + = New Progresschangedeventhandler (bw_progresschanged );} Private   Void Bw_progresschanged ( Object Sender, progresschangedeventargs e) {message. Items. insert (0, String . Format ( "Server return: {0} Control: {1} Time: {2} thread: {3 }" , E. userstate, message. gethashcode (), datetime. Now, E. userstate. tostring ()));} Private   Void S_doworkcompleted ( Object Sender, servicereference1.doworkcompletedeventargs e) {BW. reportprogress (0, E. Result );} Private   Void Bw_dowork ( Object Sender, doworkeventargs e ){ While (! Bw. cancellationpending) {var threadid = ( Int ) E. argument; S. doworkasync (threadid. tostring (), threadid); thread. Sleep (1000 );}} Private   Void Childwindow_loaded ( Object Sender, routedeventargs e) {interlocked. increment ( Ref Threadnum); BW. runworkerasync (threadnum );} Private   Void Childwindow_closed ( Object Sender, eventargs e) {BW. cancelasync ();}}}

Of course, although the title of this article is Silverlight, it is the same for winform, but the thread. Abort () of Silverlight does not work. In short, there are two points: 1. Sometimes, you cannot take it for granted or rely on experience. You can only know the result after actual verification. 2. Write.. net programs cannot be released without worry. for resources such as threads, network links, and a large amount of memory allocation, more attention is needed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.