后台StreamSocketListener只运行一次

时间:2017-02-25 17:24:19

标签: c# uwp

我在后台任务中注册了StreamSocketListener

当收到请求时,Run方法开始。

第一次运行良好,第二次出现错误:

  

O identificador deobjetonãaresentaumobjetaválido。 (HRESULT异常:0x800710D8)

完整的代码是:

public async void Run(IBackgroundTaskInstance taskInstance)
{
    var deferral = taskInstance.GetDeferral();
    var details = (SocketActivityTriggerDetails)taskInstance.TriggerDetails;
    var socketInformation = details.SocketInformation;
    try
    {
        ShowToast(details.Reason.ToString());
        if (details.Reason == SocketActivityTriggerReason.ConnectionAccepted &&
            socketInformation.SocketKind == SocketActivityKind.StreamSocketListener)
        {
            using (IOutputStream output = socketInformation.StreamSocket.OutputStream)
            {
                string str = "Tudo certo\r\n";
                var conteudo = $"HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: {str.Length}\r\n\r\n{str}";
                using (Stream stream = output.AsStreamForWrite())
                {
                    var bodyArray = Encoding.UTF8.GetBytes(conteudo);
                    stream.Write(bodyArray, 0, bodyArray.Length);
                }
            }
        }
    }
    catch (Exception e)
    {
        ShowToast(e.Message);
        StreamSocketListener socket = new StreamSocketListener();
        socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.DoNotWake);
        await socket.BindServiceNameAsync("8080");
        await socket.CancelIOAsync();
        socket.TransferOwnership("Teste");
    }
    deferral.Complete();
}

1 个答案:

答案 0 :(得分:1)

根据TransferOwnership类的StreamSocket方法的评论:

  

当应用程序即将被暂停时,或者在后台任务结束时,您的应用应调用此方法将StreamSocket的所有权转移到套接字代理服务

因此,在您的背景结束时,您应该调用TransferOwnership方法。您只能在catch块中调用它,如果您的代码段尝试成功,则不会调用TransferOwnership。您应该能够在try块的最后一次调用该方法,或者在try和catch之后调用此方法以确保将StreamSocket的所有权转移到套接字代理服务。

我在您身边复制了您的问题,并通过将socket.TransferOwnership("Teste");添加到try块的最后一位来解决问题。

try
{
    ShowToast(details.Reason.ToString());
    if (details.Reason == SocketActivityTriggerReason.ConnectionAccepted &&
        socketInformation.SocketKind == SocketActivityKind.StreamSocketListener)
    {
        using (IOutputStream output = socketInformation.StreamSocket.OutputStream)
        {
            string str = "Tudo certo\r\n";
            var conteudo = $"HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: {str.Length}\r\n\r\n{str}";
            using (Stream stream = output.AsStreamForWrite())
            {
                var bodyArray = Encoding.UTF8.GetBytes(conteudo);
                stream.Write(bodyArray, 0, bodyArray.Length);
            }
        }
    }
    socket.TransferOwnership("Teste");
}

更多详情请参阅official sample