user4244969
user4244969

Reputation:

Background thread in Windows Phone 8.1

I'm working on a Windows Phone 8.1 app and I'm want to run a (potentially very long) while loop in the background. I've read several forum posts here and elsewhere, but none actually seem to resemble what I want to do. The idea is that I'm connected to a server using a StreamSocket, and the server sends an unknown number of GUIDs (could be 2, could be 1000). When the server sends a special one (for example, all zeroes), I want to break out of the while loop, but there may be other conditions that stop the while loop as well. Since good old System.Threading.Thread is not available, I'll need some other way to do this.

I've seen this post on SO: How to create a Thread in windows phone 8.1. This post links here: https://msdn.microsoft.com/en-us/library/windows/apps/jj248672.aspx. Under "Best practices" Microsoft say not to use async/await on anything that runs on the ThreadPool, which complicates things further.

I see two potential solutions:

There could be some other way, but I've been at this for the entire day, so my brain is probably fried... thanks in advance though!

Upvotes: 2

Views: 281

Answers (1)

kiewic
kiewic

Reputation: 16390

You can use System.Threading.Tasks.Task to keep reading from an IInputStream without using an infinite loop:

private async void Foo()
{
    StreamSocket streamSocket = new StreamSocket();
    await streamSocket.ConnectAsync(new HostName("localhost"), "8888");

    IBuffer buffer = new Windows.Storage.Streams.Buffer(16);
    IInputStream inputStream = streamSocket.InputStream;

    Task<IBuffer> readTask = inputStream.ReadAsync(
        buffer,
        buffer.Capacity,
        InputStreamOptions.None).AsTask();
    var notAwait = readTask.ContinueWith(ReadMore, streamSocket);
}

private void ReadMore(Task<IBuffer> task, object state)
{
    StreamSocket streamSocket = state as StreamSocket;

    if (task.Status != TaskStatus.RanToCompletion)
    {
        // TODO: Handle error.
        return;
    }

    IBuffer buffer = task.Result;
    Guid guid = new Guid(buffer.ToArray());
    Debug.WriteLine(guid);

    if (guid == Guid.Empty)
    {
        // Close socket and stop reading.
        streamSocket.Dispose();

        return;
    }

    IInputStream inputStream = streamSocket.InputStream;

    Task<IBuffer> readTask = inputStream.ReadAsync(
        buffer,
        buffer.Capacity,
        InputStreamOptions.None).AsTask();
    var notAwait = readTask.ContinueWith(ReadMore, streamSocket);
}

Upvotes: 2

Related Questions