我应该怎么做使用任务< T>在.NET 2.0? [英] What should I do to use Task<T> in .NET 2.0?

查看:133
本文介绍了我应该怎么做使用任务< T>在.NET 2.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 4.0具有包含好的任务类来封装aynchronous编程模型的第三方物流。我工作的一个应用程序,必须是.NET 2.0,但我想避免重写任务。有什么建议?

.NET 4.0 has the TPL which contains the nice Task class to encapsulate aynchronous programming models. I'm working on an app that must be .NET 2.0, but I want to avoid rewriting Task. Any suggestions?

推荐答案

我知道你说你不希望重写工作,但实际上你可以创造一些非常简单的使用闭包,其行为有点像一个任务对象。这是我使用:

I know you said you dont want to rewrite Task, but you can actually create something fairly simple using closures, which behaves somewhat like a Task object. This is what I use:

    public delegate R AsyncTask<R>();

    public static AsyncTask<R> BeginTask<R>(AsyncTask<R> function)
    {
        R retv = default(R);
        bool completed = false;

        object sync = new object();

        IAsyncResult asyncResult = function.BeginInvoke(
                iAsyncResult =>
                {
                    lock (sync)
                    {
                        completed = true;
                        retv = function.EndInvoke(iAsyncResult);
                        Monitor.Pulse(sync); 
                    }
                }, null);

        return delegate
        {
            lock (sync)
            {
                if (!completed)               
                {
                    Monitor.Wait(sync); 
                }
                return retv;
            }
        };
    }

它的一个功能,您传递的委托调用的BeginInvoke(),并返回时调用的块并等待传递函数的结果函数。你必须创建这个函数的不同方法重载签名,当然。

Its a function that calls BeginInvoke() on the delegate you pass in, and returns a function that when called blocks and waits for the result of the function passed in. You'd have to create overloads of this function for different method signatures, of course.

走一条路,你可以调整到您的需要,并添加其他行为太喜欢延续等。关键是使用闭包和匿名委托。应该在.NET 2.0。

One way to go, you can tweak this to your needs, and add other behaviors too like Continuations, etc. The key is to use closures and anonymous delegates. Should work in .NET 2.0.

修改 - 这是你将如何使用它:

EDIT - Here is how you would use it:

    public static string HelloWorld()
    {
        return "Hello World!"; 
    }

    static void Main(string[] args)
    {
        var task = BeginTask(HelloWorld); // non-blocking call

        string result = task(); // block and wait

    }

这篇关于我应该怎么做使用任务&LT; T&GT;在.NET 2.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆