using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;namespace WindowsApplication1
{
public partial class Form1 : Form {
bool BF = true;
private delegate void setTestDelegate(int n);
void play_music(int n)
{
int i = 1;
BF = true;
while (i <= n && BF)
{
textBox1.Text = i.ToString();
i++;
}
} public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
setTestDelegate dlTest = new setTestDelegate(play_music);
IAsyncResult iaResult = dlTest.BeginInvoke(10000,null, null); //开始异步调用
if (iaResult.IsCompleted)
{
//完了后结束异步调用
dlTest.EndInvoke(iaResult);
} for (int j = 1; j <= 30000; j++) //为何要该循环执行完才调用异步函数play_music
{
textBox2.Text = j.ToString(); }
} private void button2_Click(object sender, EventArgs e)
{
BF = false;
}
}}最近在学习异步调用函数,个人理解的是,当异步调用待执行函数后,不理会该函数,继续后面的操作...
但问题是为何我测试时觉得被调用的函数并没有立即执行,而是在调用方后面的任务完成后才执行的..
本例为 //循环执行完了,异步函数play_music才有结果(文本框内容从1至10000)
谢谢!!
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;namespace WindowsApplication1
{
public partial class Form1 : Form {
bool BF = true;
private delegate void setTestDelegate(int n);
void play_music(int n)
{
int i = 1;
BF = true;
while (i <= n && BF)
{
textBox1.Text = i.ToString();
i++;
}
} public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
setTestDelegate dlTest = new setTestDelegate(play_music);
IAsyncResult iaResult = dlTest.BeginInvoke(10000,null, null); //开始异步调用
if (iaResult.IsCompleted)
{
//完了后结束异步调用
dlTest.EndInvoke(iaResult);
} for (int j = 1; j <= 30000; j++) //为何要该循环执行完才调用异步函数play_music
{
textBox2.Text = j.ToString(); }
} private void button2_Click(object sender, EventArgs e)
{
BF = false;
}
}}最近在学习异步调用函数,个人理解的是,当异步调用待执行函数后,不理会该函数,继续后面的操作...
但问题是为何我测试时觉得被调用的函数并没有立即执行,而是在调用方后面的任务完成后才执行的..
本例为 //循环执行完了,异步函数play_music才有结果(文本框内容从1至10000)
谢谢!!
至于托管线程池是什么时候开始你的工作?——不得而知
你得到的那个结论可以认为是巧合,即时一直是那个结论,那只能说是托管线程池实现上的巧合,不保证以后一直会是这个结果
你并不知道线程池到底在什么时候开始你的工作,只能说“尽快”就会开始
并且注意,特别轻量级且频繁的工作不宜异步,开新线程毕竟是昂贵的