Search code examples
c#.netparse-platform

Parse .net SDK Get Object


I have been trying to return the string of the result but it doesn't return anything. When I do Console.WriteLine it shows the link.

But the line:

s = nzk.Get<string>("link");

doesn't do anything, and I don't know why.

Here's my code:

public string getlink(String ID)
{
    ParseClient.Initialize(new ParseClient.Configuration
    {
        ApplicationId = "xxxxxxxxxxxxxx5335c1fxxx0f19efxxxx06787e",
        Server = "http://api.assintates.net/parse/"
    });
    string s = "";
    ParseQuery<ParseObject> query = ParseObject.GetQuery("test");
    query.GetAsync(ID).ContinueWith(t =>
    {
        ParseObject nzk = t.Result;
        Console.WriteLine(nzk.Get<string>("link"));  // this works 
        s = nzk.Get<string>("link");// this doesn't work 
    });
    return s;
}


class Program
{
    static void Main(string[] args)
    {

        g_get x = new g_get();
        Console.WriteLine(x.getlink("iLQLJKPoJA")); // shows nothing since i initialized the s with ""
        Console.ReadLine();

    }
}

Solution

  • Here is a little example to demonstrate your problem:

    static void Main(string[] args)
    {
        Console.WriteLine(GetString());
    
        Console.ReadLine();
    }
    
    private static async Task TimeConsumingTask()
    {
        await Task.Run(() => System.Threading.Thread.Sleep(100));
    }
    
    private static string GetString()
    {
        string s = "I am empty";
        TimeConsumingTask().ContinueWith(t =>
        {
            s = "GetString was called";
        });
    
        return s;
    }
    

    Your output will be the following:

    I am empty
    

    Why? The thing to deal with is the ContinueWith()-function (see msdn). ContinueWith returns you the Task-object. You have to await this task and in your code you didn't await it.

    So simple solution call wait on your Task-object.

        string s = "";
        ParseQuery<ParseObject> query = ParseObject.GetQuery("test");
        query.GetAsync(ID).ContinueWith(t =>
        {
            ParseObject nzk = t.Result;
            Console.WriteLine(nzk.Get<string>("link"));  // this works 
            s = nzk.Get<string>("link");// this doesn't work 
        }).Wait();
        return s;
    

    Here some more information about asynchronous programming in C#.

    Edit: Some more information

    You will see the console output because your task will be run anyway. But it will be run after you returned your string.