简体   繁体   中英

Why should I use Result in Tasks C#?

I've seen that when you use Task Class like this:

 Task<Test> task2 = Task<Test>.Factory.StartNew(() =>
            {
                string s = ".NET";
                double d = 4.0;
                for (int i = 0; i < 3; i++) { }
                return new Test { Name = s, Number = d };
            });

You can use Test tt = task2.Result; to get a result back from a Task . However, the thread does not run in background, my whole program waits for it to stop and send the data back, so why should I even use this? I can simply use a function.

So, for me to get a result back I need to run another task that will run this task? (or another thread, doesn't matter).

Is there any way to not wait and still get result?

Any way to not wait and still get result?

No, because there isn't a result until the task has completed.

The point is that you can maintain a reference to the task, perform some other operations, and then get the result.

Note that C# 5 makes it a lot easier to chain asynchronous operations together using async and await - that way when operation X needs to wait for operation Y to complete, it can await it, and the caller of operation X gets a task representing that ongoing operation... when Y has completed, X will resume, and when that completes, the task returns to the caller will also complete.

Any way to not wait and still get result?

Yes, you would use a continuation. This can be scheduled to run on the current synchronization context (so if you're in a UI application, the UI thread), as well.

This would look like:

Task<Test> task2 = Task.Factory.StartNew(() =>
{
    string s = ".NET";
    double d = 4.0;
    for (int i = 0; i < 3; i++) { }
    return new Test { Name = s, Number = d };
});

task2.ContinueWith(t =>
{
    // This runs when things are done
    Test tt = t.Result;
    // use tt
}, TaskScheduler.FromCurrentSynchronizationContext());

If you are using C# 5 and .NET 4.5, this becomes far simpler:

Test tt = await Task.Run(() =>
{
    string s = ".NET";
    double d = 4.0;
    for (int i = 0; i < 3; i++) { }
    return new Test { Name = s, Number = d };
});

// use tt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM