在任务中保持记忆离散

时间:2011-04-13 20:47:55

标签: asp.net thread-safety

我过去听说很多关于如何使用线程和任务进行编程对于天真的人来说非常危险。好吧,我很天真,但我有时需要学习。我正在制作一个程序(实际上,它是ASP.Net的通用处理程序)需要调用第三方并等待响应。在等待的时候,我想让处理程序继续做其他事情,所以我试图弄清楚如何异步地执行第三方Web请求。根据我收到的其他一些问题的答案,这里是我提出的问题,但我想确保在我的处理程序多次同时调用时不会遇到大问题。

为了测试这个,我构建了一个控制台项目。

class Program
{
    static void Main(string[] args)
    {
        RunRequestAsynch test = new RunRequestAsynch();
        test.TestingThreadSafety = Guid.NewGuid().ToString();

        Console.WriteLine("Started:" + test.TestingThreadSafety);

        Task tTest = new Task(test.RunWebRequest);
        tTest.Start();

        while (test.Done== false)
        {
            Console.WriteLine("Still waiting...");
            Thread.Sleep(100);
        }

        Console.WriteLine("Done. " + test.sResponse);

        Console.ReadKey();
    }
}

我实例化一个单独的对象(RunRequestAsynch),在其上设置一些值,然后启动它。虽然这是处理我只是输出一个字符串到控制台窗口。

public class RunRequestAsynch
{
    public bool Done = false;
    public string sResponse = "";
    public string sXMLToSend = "";

    public string TestingThreadSafety = "";

    public RunRequestAsynch() { }


    public void RunWebRequest()
    {
        Thread.Sleep(500);
        // HttpWebRequest stuff goes here
        sResponse = TestingThreadSafety;
        Done = true;
        Thread.Sleep(500);

    }
}

所以......如果我同时运行1000个,我可以指望每个实例都有自己的内存和属性,对吗?那条线“Done = true;”不会触发,然后Generic Handler的每个实例都会死掉,对吗?

我写了一个.bat文件来运行几个实例,我在每个特定对象上设置的guid对于每个实例似乎保持不变,这就是我想要的......但我想确保我不是做一些非常愚蠢的事情会让我在满负荷的情况下咬我。

1 个答案:

答案 0 :(得分:1)

我没有看到任何明显的问题,但你应该consider using the Factory.StartNew instead of Start。每个任务只执行一次,因此同时运行多个任务没有任何问题。

如果你想简化你的代码并利用Factory.StartNew,在你的处理程序中你可以做这样的事情(从我记得你的上一个问题):

Task<byte[]> task = Task.Factory.StartNew<byte[]>(() =>    // Begin task
{
    //Replace with your web request, I guessed that it's downloading data
    //change this to whatever makes sense
    using (var wc = new System.Net.WebClient())
        return wc.DownloadData("Some Address");
});

//call method to parse xml, will run in parallel

byte[] result = task.Result;  // Wait for task to finish and fetch result.