Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 等待另一种方法_C#_.net_Asynchronous_Async Await - Fatal编程技术网

C# 等待另一种方法

C# 等待另一种方法,c#,.net,asynchronous,async-await,C#,.net,Asynchronous,Async Await,我想我需要异步等待我的程序,但我不知道怎么做。从GetData方法中,我需要将请求发送到套接字,最后将套接字数据发送到同一个方法。需要以某种方式将数据从OnReceive传递到初始GetData方法。是否可以在此处实现等待异步任务?以下是简化方案: AsyncCallback m_pfnLookupCallback; Socket m_sock; public void GetData() { string data; if (condi

我想我需要异步等待我的程序,但我不知道怎么做。从GetData方法中,我需要将请求发送到套接字,最后将套接字数据发送到同一个方法。需要以某种方式将数据从OnReceive传递到初始GetData方法。是否可以在此处实现等待异步任务?以下是简化方案:

AsyncCallback m_pfnLookupCallback;
    Socket m_sock;

    public void GetData()
    {
        string data;
        if (condition) data = GetDataFromCache();
        else data = GetDataFromNet(); /// !NEED AWAIT FOR SOCKET DATA HERE

        //will process data here.

    }

    public string GetDataFromNet()
    {
        m_sock.Send(szCommand, iBytesToSend, SocketFlags.None);
        WaitForData("s1");
    }
    public void WaitForData(string sSocketName)
    {
            m_pfnLookupCallback = new AsyncCallback(OnReceive);
            m_sock.BeginReceive(m_szLookupSocketBuffer, 0, m_szLookupSocketBuffer.Length, SocketFlags.None, m_pfnLookupCallback, sSocketName);
    }

    private void OnReceive(IAsyncResult asyn)
    {
        int iReceivedBytes = 0;
        iReceivedBytes = m_sockLookup.EndReceive(asyn);
        string sData = Encoding.ASCII.GetString(m_szLookupSocketBuffer, 0, iReceivedBytes); //WHAT I NEED
    }

p、 如果可能的话,我会避免更改套接字工作,因为它们在程序的其他部分中使用。

您可以很容易地将旧的IAsyncResult模式(APM)转换为异步等待。下面是套接字调用的一个示例:

var byteCount = await Task.Factory.FromAsync(
    (callback, s) =>
    {
        return clientSocket.BeginReceive(
            m_szLookupSocketBuffer, 
            0, 
            cm_szLookupSocketBuffer.Length,
            SocketFlags.None, 
            callback,
            sSocketName);
    },
    result => clientSocket.EndReceive(result),
    null);

您可以在任务中始终包装需要很长时间才能完成的代码。运行并等待。您永远不应该这样做@菲利普