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

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

View Full Document Right Arrow Icon
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
Background image of page 1

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

View Full DocumentRight Arrow Icon
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.
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

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 Right Arrow Icon
Ask a homework question - tutors are online