ThreadPool.QueueUserWorkItem 方法 (WaitCallback)
说明:将方法排入队列以便执行,WaitCallback,表示要执行的方法。如果将方法成功排入队列,则为 true;否则为 false。
示例:addtest方法需要比较长的时间来响应,因此在button1_Click被点击以后,程序会失去响应,使用ThreadPool.QueueUserWorkItem 后,页面会继续响应其他时间,等addtest执行结束后,响应结果。
<Window x:Class="WpfAppThread.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Button Height="23" HorizontalAlignment="Left" Margin="9,23,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">ButtonOne</Button>
<Button Height="23" Margin="102,23,101,0" Name="button2" VerticalAlignment="Top" Click="button2_Click">ButtonTwo</Button>
</Grid>
</Window>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Button Height="23" HorizontalAlignment="Left" Margin="9,23,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">ButtonOne</Button>
<Button Height="23" Margin="102,23,101,0" Name="button2" VerticalAlignment="Top" Click="button2_Click">ButtonTwo</Button>
</Grid>
</Window>
private void button1_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(addtest),"Testaa");
//addtest();
}
private void addtest(object aa)
{
long result=0;
for (int i = 0; i < 1000000000; i++)
{
result += i;
}
MessageBox.Show(result.ToString()+aa.ToString());
}
private void button2_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("two");
}
{
ThreadPool.QueueUserWorkItem(new WaitCallback(addtest),"Testaa");
//addtest();
}
private void addtest(object aa)
{
long result=0;
for (int i = 0; i < 1000000000; i++)
{
result += i;
}
MessageBox.Show(result.ToString()+aa.ToString());
}
private void button2_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("two");
}