Lec20

# Lec20 - Lecture 20 Threading PIC 10C Todd Wittman Resource...

This preview shows pages 1–4. Sign up to view the full content.

1 Lecture 20: Threading PIC 10C Todd Wittman Resource Hogs s If we have a procedure that takes a really long time, it freezes up our program until that function is complete. s The controls will not work and we cannot even close the program gracefully. s Ex Calculate the first N prime numbers and display the results in a ListBox. s To calculate the first 20,000 primes takes almost a minute. s During the calculation, the ListBox is blank and the buttons don't work. PrimesBox CalculateButton textBox1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Example: Prime Numbers private void CalculateButton_Click(object sender, EventArgs e) { PrimesBox.Items.Clear(); int numPrimes = int.Parse(textBox1.Text); int numPrimesFound = 0; long lastPrime = 1; while (numPrimesFound < numPrimes) { lastPrime++; if (isPrime(lastPrime)) { numPrimesFound++; PrimesBox.Items.Add("Prime #" + numPrimesFound.ToString() + " is " + lastPrime.ToString()); } } } private bool isPrime(long x) { for (long i = 2; i < x; i++) if (x%i == 0) return false; return true; } Can you make the isPrime function more efficient? Threading s To prevent the calculation from freezing up our program, we can run the primes calculation on a different thread from the main UI thread. s Essentially, we will start a different procedure in the background that will run concurrently with our GUI procedure. s The BackgroundWorker control enables us to create a separate thread. It is an invisible control, like the Timer. s You can think of the Timer as being a special case of a background thread.
3 BackgroundWorker Properties s WorkerReportsProgress -- bool that determines if the thread will give periodic updates or if we will wait until the thread is complete. False by default. s

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 05/18/2010 for the course PIC 10C taught by Professor Wittman during the Spring '10 term at UCLA.

### Page1 / 9

Lec20 - Lecture 20 Threading PIC 10C Todd Wittman Resource...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online