2

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();

    }
}
2
  • How do you consume getlink in your application? Can you provide some more details? Commented Nov 4, 2017 at 15:44
  • edited the code :) Commented Nov 4, 2017 at 16:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ahhh, thank you so much, sorry i just shifted from java so i'm still learning c#. thank you again !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.