How can I implement my own async callback in C# wp

2019-08-30 06:15发布

问题:

I am trying to port an engine into C# WP7 silverlight, along with its unit tests. Because it uses http requests, it needs to be asynchronous as dictated by the framework. The Android version of the engine I am porting uses synchronous blocking sockets on a worker thread. It invokes a callback whenever the entire operation is complete (not just the http request).

Question - how can I wrap the callback mechanism so that it does an asynch callback that can be used in an [Asynchronous] unit test?

I want it to do something like this:

using System;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Silverlight.Testing;

[TestClass]
public class WebRequestsTests : WorkItemTest
{
    [TestMethod, Asynchronous]
    public void TestWebRequest()
    {
        var webRequest = WebRequest.CreateHttp("http://www.stackoverflow.com");

        webRequest.BeginGetResponse(result =>
        {
            EnqueueCallback(() =>
            {
                WebResponse response = webRequest.EndGetResponse(result);

                // process response 

                TestComplete(); // async test complete 
            });
        }, null);
    }
} 

Do I need to implement the IAsync interface or something similar?

I'd like to have it do something like this:

using System;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Silverlight.Testing;

[TestClass]
public class WebRequestsTests : WorkItemTest
{
    [TestMethod, Asynchronous]
    public void TestWebRequest()
    {
        MyThread thread = new MyThread();

        thread.Start(result =>
        {
            EnqueueCallback(() =>
            {
                WebResponse response = thread.EndGetResult(result);

                // process response 

                TestComplete(); // async test complete 
            });
        }, null);
    }
} 

Not sure I'm also 100% comfortable with the lambda expressions either, so if those are removed, even better! ;)

Thanks

回答1:

You don't need to create a new thread to deal with the EndRequest or EndResponse callback - these will be called for you on a background thread from the ThreadPool. So something like your first code example should work.

If you don't like the nested lambdas just declare named methods :). You can pass state information in the Begin... methods which you can retrieve in the result object.

What you're asking is kind of weird - you're wrapping an async framework with sync version, and rewrapping that with an async version. It sounds like you're creating extra work for yourself in order to stay faithful to your port. You will also use some extra memory to keep an extra thread alive doing nothing (1MB for the stack at least).

If you still want to do it check out this link though.