c# return 来自异步函数的数据

c# return data from Asynchronous function

我有两种方法

public void GetEmp()
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new System.Uri("http://sdw2629/empservice/EmployeeInfo.svc/Employee"));
    request.Method = "GET";
    request.ContentType = "application/json; charset=utf-8";

    request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);  

}

private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
    HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
    using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult))
    {
        using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
        {
            string results = httpwebStreamReader.ReadToEnd();
            //execute UI stuff on UI thread.              
        }
    }
}  

这里我想 return 一个字符串 "results" 到像这样的其他方法

string data= obj1.GetEmp()

我怎样才能做到这一点..任何帮助都会得到帮助..谢谢

最简单的方法是使用 async 重写方法,如下所示:

public async Task<string> GetEmpAsync()
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new System.Uri("http://sdw2629/empservice/EmployeeInfo.svc/Employee"));
    request.Method = "GET";
    request.ContentType = "application/json; charset=utf-8";
    var response = await request.GetResponseAsync();
    using (StreamReader httpwebStreamReader = new StreamReader(response.GetResponseStream()))
    {
        string results = await httpwebStreamReader.ReadToEndAsync();
        //execute UI stuff on UI thread.
        return results;
    }

}

然后你可以用这样的代码得到结果:

var results = await GetEmpAsync();

如果您使用的是旧版本并且没有async,您可以通过阻塞方式来获得结果:

public string GetEmpBlocking()
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new System.Uri("http://sdw2629/empservice/EmployeeInfo.svc/Employee"));
    request.Method = "GET";
    request.ContentType = "application/json; charset=utf-8";
    var response = request.GetResponse();
    using (StreamReader httpwebStreamReader = new StreamReader(response.GetResponseStream()))
    {
        string results = httpwebStreamReader.ReadToEnd();
        //execute UI stuff on UI thread.
        return results;
    }
}

得到这样的结果:

var results = GetResultBlocking();

Р.S.您也可以考虑使用 Microsoft.Bcl.Async 来支持早期版本中的 async

只需使用

var resp = request.GetResponse();

而不是

request.BeginGetResponse(...);

使用同步 GetResonse,您可以直接 return 字符串。

public string GetEmp()
{
    var request = (HttpWebRequest)HttpWebRequest.Create(new System.Uri(@"http://.../data.json"));
    request.Method = "GET";
    request.ContentType = "application/json; charset=utf-8";

    var resp = request.GetResponse();

    using (var httpWebStreamReader = new StreamReader(resp.GetResponseStream()))
    {
        var result = httpWebStreamReader.ReadToEnd();
        return result;
    }
}