I have some functionality that needs to be async in my C# app. It's a fairly simple workflow so I don't need to get fancy with it I basically need the equivalent of jQuery.Deferred.
My method should return an object that people can attach success and failure handlers to. Either the success or failure handler will fire exactly once. I also need a way to trigger the success/fail when the async process completes.
So I want something like this:
var asyncTask = ReadSomeStatsFrom("a-really-big-file.txt");
asyncTask.OnSuccess += (stats) => Console.WriteLine("Completed " +stats.ToString());
asincTask.OnFail += (err) => Console.WriteLine("Uh Oh "+err.ToString());
//return control to the calling method and go on to do other stuff
Yes I can create threads and simulate this sort of thing as I did last time I needed this functionality years ago but isn't there' new stuff to make this all neater by now? I've been hearing about Rx and it seems to be addressing similar problem areas (and obviously a lot more).
So question 1: Am I on the right track in looking into Rx for this functionality? If not what I should look into.
and question 2: How would the above example look with rx, including actually signifying that the task succeeded or ended inside ReadSomeStatsFrom()
Have a look at the Task Paralel Library too. It ships with the clr, and it is abetter fit for your needs. Rx is for streams of events primarily, not single ones.
I have seen a sample where an async io (your file read) is wrapped in a tpl task almost directly, but that could be a 4.5 feature.
Rx seems perfectly well suited for your needs.
If ReadSomeStatsFrom
can be written synchronously then try this:
Observable
.Start(() => ReadSomeStatsFrom("a-really-big-file.txt"))
.Subscribe(
stats => Console.WriteLine("Completed " + stats.ToString()),
err => Console.WriteLine("Uh Oh " + err.ToString()));
I agree that TPL may be a good fit too, but Rx can be more expressive than TPL in many ways.
The Task Parallel Library is what you are looking for, the link here http://msdn.microsoft.com/en-us/library/ee372288.aspx will explain the features of the library.
Specifically, you want to look at handling your response as a continuation which is discussed on the page.