AiNoTame

...for love
posts - 9, comments - 40, trackbacks - 0

Multithreading with WPF

Voglio qui riassumere due concetti “base” (nel senso che non li approfondisco molto) riguardo il multithreading con wpf. In particolare due concetti:

  1. Eseguire componenti UI su thread diversi
  2. Aggiornare componenti di UI da thread diversi

Per far questo ho scritto una semplice finestra con il seguente contenuto:

<Button Content="Start another Window with same UI Thread"

Margin="5,5,5,2" Click="btnSameThread_Click" /> <Button Content="Start another Window with different UI Thread"

Margin="5,2,5,2" Click="btnNewThread_Click" /> <Button Content="Perform Long Operation"

Margin="5,10,5,10" Click="btnLongOperation_Click" /> <Button Content="Change Textbox of last window opened"

Margin="5,5,5,2" Click="btnChangeTextLastWindow_Click" /> <Button Content="Change Textbox of last window opened (secured)"

Margin="5,2,5,5" Click="btnChangeTextLastWindowSecured_Click" /> <TextBox Text="Try change this text" x:FieldModifier="public" x:Name="ChangeTextbox"
/>

 

Da notare l’ultima textbox con x:FieldModifier=”public”; in questo modo la textbox è accessibile anche dall’esterno della classe (in questo caso non serve, ma l’esempio deriva da un caso in cui il thread era su una classe esterna).

Ecco il codice:

MainWindow lastWindowOpened = null;
private void btnSameThread_Click(object sender, RoutedEventArgs e)
{
    lastWindowOpened =  new MainWindow(); //show window with same Thread
    lastWindowOpened.Show(); } private void btnNewThread_Click(object sender, RoutedEventArgs e) {
   Thread t = new Thread(new ThreadStart(() => 
   {
        lastWindowOpened = new MainWindow(); //the window is created in a different thread
        lastWindowOpened.Show(); //show window
        lastWindowOpened.Closed +=

(s, ec) => System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
        System.Windows.Threading.Dispatcher.Run(); //start message loop!
    }));
     t.SetApartmentState(ApartmentState.STA);//interoperability with com…
    t.Start(); } private void btnLongOperation_Click(object sender, RoutedEventArgs e) { Thread.Sleep(5000); } private void btnChangeTextLastWindow_Click(object sender, RoutedEventArgs e) {
//not safe for UI running on different thread
     lastWindowOpened.ChangeTextbox.Text = "Cambio da altra window"; } private void btnChangeTextLastWindowSecured_Click(object sender, RoutedEventArgs e) {
     lastWindowOpened.Dispatcher.BeginInvoke(new Action(() =>
     {//if closed, if not null…
         lastWindowOpened.ChangeTextbox.Text = "Cambio da altra window";
     })); }

Ora occorre capire due concetti:

  1. btnNewThread esegue un thread in cui mostra una nuova finestra. Il thread tuttavia non ascolta gli eventi della UI finché non si esegue Dispatcher.Run() (http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.run.aspx). Eseguendo il metodo statico, il thread corrente entra nel loop dei messaggi finché non si esegue InvokeShutdown(). Cosa succede se non si chiama InvokeShutdown()? La finestra viene chiusa, ma il thread continua ad ascoltare il loop dei messaggi per sempre. Quindi il thread non termina e l’applicazione resta appesa. TaskManager e killiamo Smile
  2. btnChangeTextLastWindowSecured modifica il contenuto della textbox dell’ultima window aperta. In questo caso si “inietta” un delgate al thread che “possiede” l’elemento di UI. In qusto modo l’operazione viene eseguita dal thread affine alla UI senza creare problemi.

Ora il momento dei test:

  1. lanciamo la finestra, premiamo il primo bottone per lanciare una nuova window. Ora nella prima premiamo btnLongOperation e muoviamo le finestre…
    Non si muovono! questo perchè le due finestre sono gestite dallo stesso thread che viene posto in sleep(). Corretto.
  2. lanciamo la finestra, premiamo il secondo bottone e poi btnLongOperation su una finestra e muoviamo l’altra…
    Si muove! questo perchè le due finestre sono su due thread diversi e se si pone un thread in sleep mode, quella finestra è bloccata, ma l’altra no ed è libera di leggere i messaggi dal loop e quindi muovere la window.
  3. riprendiamo il secondo punto. Lanciamo due window su thread diversi e premiamo il 4° button. L’applicazione crasha. Questo perchè si accede ad un elemento di UI appartenente ad un altro thread. L’ultimo button è necessario.
  4. Ultimo punto, un po’ più complicato…
    1. Lanciamo una window
    2. Lanciamo la seconda window su un thread diverso con il secondo button
    3. sulla seconda window eseguiamo btnLongOperation. La seconda window è quindi bloccata e non si può muovere.
    4. Ora nella prima window premiamo l’ultimo button… cosa succede?
      Niente. Il thread della prima window continua il loop dei messagge ed è libera. La seconda finestra è bloccata. Il testo non cambia fino a che il secondo thread non esce dallo sleep.
    5. Cosa succede se invece di BeginInvoke mettiamo Invoke? In questo caso anche il primo thread si blocca perchè l’invoke è sincrono e attende l’esecuzione dell’altro thread.

Liberi di eseguire altre prove (e postare esempi interessanti) Smile

Print | posted on Thursday, March 31, 2011 12:33 AM | Filed Under [ Multithread ]

Feedback

Gravatar

# re: Multithreading with WPF

People can learn referring to this topic therefore, I propose to find the writing service and buy an essay moreover, that is possible to see custom essay.
9/30/2011 4:20 AM | Salinas22Terri
Gravatar

# re: Multithreading with WPF

According to my own monitoring, thousands of persons in the world receive the personal loans from well known banks. Thus, there's a good possibility to find a consolidation loan in any country.
10/9/2011 5:52 AM | CarolineVaughn25
Gravatar

# re: Multithreading with WPF

Hi there! I was so excited to have my wedding party final year and the a lot more I searched for the right wedding dresses the a lot more I fell in love with them all. My spending budget was a bit little so I was not able to afford some of the dresses that I function in my lens.... But it does not hurt to dream and look at other bride's creativity! You can find dresses out bridesmaid dresses online there which can be merely out of this globe and some of them are very creative. So included a list of all the crazy unique dresses that I identified. I am particular that bridesmaid dresses 2012I will end up deciding on something a bit a lot more evening dresses on sale classic but I discovered these to become truly fun! This very first to become featured is dress quantity ten. This dress is so cute and full and it has bridesmaid dresses 2012 been handcrafted completely out of paper. Yes! papers. I could not think it myself but as I looked closer a the specifics and also the kind of the dress I realized it was merely paper. Remarkable, so gorgeous, so soft and so full! This dress could be the right selection for an artistic Bride.
12/28/2011 6:41 AM | hollisbattle
Gravatar

# re: Multithreading with WPF

The ancient essays paper offered by expert writing services can be noticed by all the students in web. Hence, this is possible to purchase term papers almost costless.
12/29/2011 9:37 AM | RojasBeatriz33
Gravatar

# re: Multithreading with WPF

Some of men look for required knowledge close to this good topic. Thus, that’s accomplishable to get everything at the writers job service.
2/6/2012 8:30 PM | ErickaHoover33
Gravatar

# re: Multithreading with WPF

Here is a quick thought: dealing with unknown phone calls can be annoying, right? I think we all can agree with that! Yet knowing a reverse cell phone lookup directory is available to quickly obtain the name and address associated with those calls is a major comfort to many people.
2/19/2012 5:02 PM | Red Geaery

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 7 and 6 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET