如何返回结果异步事件完成

时间:2014-03-15 14:23:12

标签: c# .net asynchronous

我有以下功能。如何在ReadCompleted之后获得正确的结果。有可能吗?我总是得到null结果。我在框架4.0上写作。

Function calling

object _result = CreateSalesOrder.GetAsyncRecords("xxxx");
console.writelen(_result); ===> null

class CreateSalesOrder
{   
    public wsRef_SalesOrder.Sales_Order GetAsyncRecords(string _strNo)
    {
        wsRef_SalesOrder.Sales_Order_PortClient _ws = GetService();
        wsRef_SalesOrder.Sales_Order _rec = null;
        _ws.ReadCompleted += delegate(object sender, wsRef_SalesOrder.ReadCompletedEventArgs e)
        {
            _rec = e.Result;
        };
        _ws.ReadAsync(_strNo);
        if (_ws.State == System.ServiceModel.CommunicationState.Opened)
            _ws.Close();
        return _rec;
    }            
}

1 个答案:

答案 0 :(得分:1)

您的GetRecordsAsync应为async。像这样:

public async Task<wsRef_SalesOrder.Sales_Order> GetAsyncRecords(string _strNo)
{
    wsRef_SalesOrder.Sales_Order_PortClient _ws = GetService();
    wsRef_SalesOrder.Sales_Order _rec = null;
    _ws.ReadCompleted += delegate(object sender, wsRef_SalesOrder.ReadCompletedEventArgs e)
    {
        _rec = e.Result;
    };
    await _ws.ReadAsync(_strNo);
    if (_ws.State == System.ServiceModel.CommunicationState.Opened)
        _ws.Close();
    return _rec;
}