您的位置:首页 > 编程语言 > C#

C#在VS2005开发环境中利用异步模式来对一个方法的执行时间进行超时控制

2017-03-24 22:00 621 查看
using System.Threading;
using System;
namespace ConsoleApplication4
{
public class Program
{
static void Main(string[] args)
{
try
{
String str = "excuting";
myDel del = new myDel(Method);
CallWithTimeout(del,1200,str);
Console.WriteLine("success");

}
catch (Exception)
{
Console.WriteLine("fail");
}
}

static void Method(String str)
{
Console.WriteLine(str);
Thread.Sleep(1000);
}

public delegate void myDel(string str);
static void CallWithTimeout(myDel del,int timeoutMilliseconds,String str)
{
ThreadStart threadStart = new ThreadStart(delegate()
{
if (null != del)
{
del(str);//委托调用
}
});
Thread thread = new Thread(threadStart);

IAsyncResult result = del.BeginInvoke(str, null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
del.EndInvoke(result);
}
else
{
thread.Abort();
throw new TimeoutException();
}
}

}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐