我有一个函数string getData(string sKey),有可能返回正确的参数,也有可能不能返回参数。如果能返回参数,执行时间只有1秒,如果不能返回参数,执行时间可能有10秒以上。问题是:怎么限制程序执行的时间,不论返回参数与否,函数执行时间限制为两秒。
我想过使用Tread线程,然后主线程sleep(2000),但是多线程不能返回值,有没有简单的办法来实现。

解决方案 »

  1.   

    自己搞定了,使用static传值。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading; 
    namespace ConsoleApplicationThread
    {    class Program
        {
            public static string value;   //线程回传值
            static void Main(string[] args)
            {            MyC c = new MyC("我是线程参数!");
                Thread th = new Thread(new ThreadStart(c.thFun));
                 th.Start();
                Thread.Sleep(3000);
                th.Abort();            Console.WriteLine(value);
                Console.ReadKey();
            }            }
     
        class MyC
        {        
            private string ss;
            public MyC(string ss)
            {
                 this.ss = ss;
            }
            public void thFun()
            {
                Console.WriteLine("线程开始.." + DateTime.Now.ToString());
                Thread.Sleep(2000);
                Program.value = this.ss;
                Console.WriteLine("线程结束.." + DateTime.Now.ToString());        }
        }
    }