Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c# - What should I do to use Task<T> in .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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
            }
        };
    }

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.

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

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...