异步和多线程测试的有关问题
异步和多线程测试的问题
这两天在做项目中用到异步方法,结果出现以下问题,以下2个程序,
用异步时显示很慢,任务管理器的线程数也比较上,
用多线程则正常,显示刷新很快,任务管理器的线程数一下上到几百。
百思不得其解,上来问问各位高手。
1.用异步
效果图
因为延迟10秒才计算出结果,正常add和结果的显示不应该这么快在一起,就是因为运行慢才会这样
2.用多线程
这两天在做项目中用到异步方法,结果出现以下问题,以下2个程序,
用异步时显示很慢,任务管理器的线程数也比较上,
用多线程则正常,显示刷新很快,任务管理器的线程数一下上到几百。
百思不得其解,上来问问各位高手。
1.用异步
using System;
using System.Threading;
namespace TestAsyncCallback
{
public delegate string GetReplyDelegate(int id, string msg);
static class Program1
{
internal static GetReplyDelegate d = null;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
d = new GetReplyDelegate(GetReplyDelay);
Start();
Console.ReadLine();
}
static string GetReplyDelay(int id, string msg)
{
Console.WriteLine("add:" + id.ToString());
Thread.Sleep(10000);
return msg + id.ToString();
}
static void Start()
{
for (int i = 1; i <= 1000; i++)
{
//ParameterizedThreadStart t = new ParameterizedThreadStart(GetReplyProc);
//Thread thread = new Thread(t);
//thread.IsBackground = true;
//thread.Start(new object[] { i, "test" });
d.BeginInvoke(i, "test", Callback, null);
}
}
static void Callback(IAsyncResult ar)
{
string s = d.EndInvoke(ar);
Console.WriteLine(s);
}
private static void GetReplyProc(object obj)
{
object[] os = (object[])obj;
string s = GetReplyDelay((int)os[0], os[1].ToString());
Console.WriteLine(s);
}
}
}
效果图
因为延迟10秒才计算出结果,正常add和结果的显示不应该这么快在一起,就是因为运行慢才会这样
2.用多线程
using System;
using System.Threading;
namespace TestAsyncCallback
{
public delegate string GetReplyDelegate(int id, string msg);
static class Program1
{
internal static GetReplyDelegate d = null;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
d = new GetReplyDelegate(GetReplyDelay);
Start();
Console.ReadLine();
}
static string GetReplyDelay(int id, string msg)
{