Advertisement
Guest User

Untitled

a guest
Oct 24th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. <Window x:Class="ThreadingPrimeNumberSample.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="Prime Numbers" Width="760" Height="500">
  5. <Grid>
  6. <Button Content="Start"
  7. Click="StartOrStop"
  8. x:Name="startStopButton"
  9. Margin="10,10,693,433"
  10. />
  11. <TextBlock Margin="87,15,547,424"><Run Text="Biggest Prime Found:"/><InlineUIContainer>
  12.  
  13. </InlineUIContainer></TextBlock>
  14. <TextBlock x:Name="bigPrime" Margin="222,15,409,428"><Run Text="3"/></TextBlock>
  15. <TextBox Height="104" TextWrapping="Wrap" Text="TextBox" Width="522" Margin="87,295,143,70"/>
  16. </Grid>
  17. </Window>
  18.  
  19.  
  20. ...usings...
  21.  
  22. namespace ThreadingPrimeNumberSample
  23. {
  24.  
  25. public partial class MainWindow : Window
  26. {
  27. public delegate void NextPrimeDelegate();
  28.  
  29. //Current number to check
  30.  
  31. private long num = 3;
  32.  
  33. private bool continueCalculating = false;
  34.  
  35. public MainWindow()
  36. : base()
  37. {
  38. InitializeComponent();
  39. }
  40.  
  41. private void StartOrStop(object sender, EventArgs e)
  42. {
  43. if (continueCalculating)
  44. {
  45. continueCalculating = false;
  46. startStopButton.Content = "Resume";
  47. }
  48. else
  49. {
  50. continueCalculating = true;
  51. startStopButton.Content = "Stop";
  52. startStopButton.Dispatcher.BeginInvoke(
  53. DispatcherPriority.Normal,
  54. new NextPrimeDelegate(CheckNextNumber));
  55. }
  56. }
  57.  
  58.  
  59. public void CheckNextNumber()
  60. {
  61.  
  62. // Reset flag.
  63. NotAPrime = false;
  64.  
  65. for (long i = 3; i <= Math.Sqrt(num); i++)
  66. {
  67. if (num % i == 0)
  68. {
  69. // Set not a prime flag to true.
  70. NotAPrime = true;
  71. break;
  72. }
  73. }
  74.  
  75. // If a prime number.
  76. if (!NotAPrime)
  77. {
  78. bigPrime.Text = num.ToString();
  79. }
  80.  
  81. num += 2;
  82.  
  83. Thread.Sleep(500);
  84.  
  85.  
  86.  
  87. if (continueCalculating)
  88. {
  89. startStopButton.Dispatcher.BeginInvoke(
  90. System.Windows.Threading.DispatcherPriority.SystemIdle,
  91. new NextPrimeDelegate(this.CheckNextNumber));
  92. }
  93. }
  94.  
  95.  
  96. private bool NotAPrime = false;
  97.  
  98.  
  99. }
  100.  
  101.  
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement