利用闲暇时间在UI线程的空闲做一些不占时间的操作(不另起线程)和利用委托新建线程实现。
代码语言:javascript复制public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private bool continueCacu = false;
public delegate void MyCacuDelegate(int a);
public delegate void MyCacuDelegate2();
private void Button_Click(object sender, RoutedEventArgs e)
{
if (continueCacu)
{
continueCacu = false;
this.StartOrStop.Content = "Resume";
}
else
{
continueCacu = true;
this.StartOrStop.Content = "stop";
StartOrStop.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new MyCacuDelegate(this.CheckNextNumber), 3);
//MyCacuDelegate dele = new MyCacuDelegate(this.CheckNextNumber);
//dele.BeginInvoke(3, null, null);
//CheckNextNumber2();
//MyCacuDelegate2 dele = new MyCacuDelegate2(CheckNextNumber2);
//dele.BeginInvoke(null, null);
}
}
public void CheckNextNumber(int num)
{
// Reset flag.
bool isPrime = true;
for (long i = 3; i <= Math.Sqrt(num); i )
{
if (num % i == 0)
{
// Set not a prime flag to ture.
isPrime = false;
break;
}
} // If a prime number.
if (isPrime)
{
//StartOrStop.Content = num;
//Thread.Sleep(1000);
this.StartOrStop.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new MyCacuDelegate((x) =>
{
this.StartOrStop.Content = x;
}), num);
}
if (continueCacu)
{
StartOrStop.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.SystemIdle,
new MyCacuDelegate(this.CheckNextNumber), num 2);
//MyCacuDelegate dele = new MyCacuDelegate(this.CheckNextNumber);
//dele.BeginInvoke(num 2, null, null);
}
}
public void CheckNextNumber2()
{
int num = 3;
while (continueCacu)
{
bool isPrime = true;
for (long i = 3; i <= Math.Sqrt(num); i )
{
if (num % i == 0)
{
// Set not a prime flag to ture.
isPrime = false;
break;
}
} // If a prime number.
if (isPrime)
{
//StartOrStop.Content = num;
Thread.Sleep(100);
this.StartOrStop.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new MyCacuDelegate((x) =>
{
this.StartOrStop.Content = x;
}
), num);
}
num = 2;
}
}
}