14

I'm trying to transition from the Event-based Asynchronous Pattern where I tracked running methods using unique id's and the asynoperationmanager.
As this has now been dropped from Windows 8 Apps I'm trying to get a similar effect with Async/Await but can't quite figure out how.
What I'm trying to achieve is something like

private async Task updateSomething()
{
    if(***the method is already running***)
    {
        runagain = true;
    }
    else
    {
        await someMethod();
        if (runagain)
        {
            run the method again
        }            
    }
}

The part I'm struggling with is finding out if the method is running. I've tried creating a Task and looking at the status of both that and the .status of the async method but they don't appear to be the correct place to look. Thanks

UPDATE: This is the current code I use in .net 4 to achieve the same result. _updateMetaDataAsync is a class based on the Event-Based Asynchronous Pattern.

private void updateMetaData()
    {
        if (_updateMetaDataAsync.IsTaskRunning(_updateMetaDataGuid_CheckAllFiles))
        {
            _updateMetaDataGuid_CheckAllFiles_Again = true;
        }
        else
        {
            _updateMetaDataGuid_CheckAllFiles_Again = false;
            _updateMetaDataAsync.UpdateMetaDataAsync(_updateMetaDataGuid_CheckAllFiles);
        }
    }

private void updateMetaDataCompleted(object sender, UpdateMetaDataCompletedEventArgs e)
    {
        if (_updateMetaDataGuid_CheckAllFiles_Again)
        {
            updateMetaData();
        }
    }

3 Answers 3

9

async/await itself is intended to be used to create sequential operations executed asynchronously from the UI thread. You can get it to do parallel operations, but generally the operations "join" back to the UI thread with some sort of result. (there's also the possibility of doing "fire-and-forget" types of asynchronous operations with await but it's not recommended). i.e. there's nothing inherent to async/await to support progress reporting.

You can get progress out of code using async/await; but you need to use new progress interfaces like IProgress<T>. For more info on progress reporting with async/await, see http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx. Migrating to this should just be a matter of calling an IProgress delegate instead of a Progress event.

2
  • I don't use Async/Await through choice, more because MS has littered the .net for windows API with Async marked methods. Is there anyway to avoid going down the async/await route?
    – Oli
    Aug 23, 2012 at 21:15
  • 4
    Just because a method ends in Async doesn't mean you have to use await. You can simply use the resultant Task and do whatever you want to do with it, like ContinueWith. e.g. webClient.DownloadStringAsync(myUri).ContinueWith(t=>Trace.WriteLine("done"));--no await. Aug 23, 2012 at 21:17
4

If you're using a Task you've created, you can check the Task's Status property (or just see Task.IsCompleted if completion is the only state you are interested in).

That being said, await will not "return" until the operation either completes, raises an exception, or cancels. You can basically safely assume that, if you're still waiting on the "await", your task hasn't completed.

6
  • Thanks Reed, Would you be able to post some code as this is exactly what I've been trying to do but status always says WaitingForActivation even though I know the task is running. I basically want 1 Task declared that I can then assign a method to in the constructor. From another class method I can then start it and check it's status, although feel free to point out a better way if there is one.
    – Oli
    Aug 23, 2012 at 19:04
  • @Oli It's generally a bad idea to have a Task that hasn't been started - the TPL and async/await is geared with the concept of tasks always being "hot", which is why Task.Run is preferred over new Task. What is the actual goal here? (Not the mechanisms, but what you're trying to accomplish) Aug 23, 2012 at 19:08
  • I've basically got a long running task that downloads information from the internet and updates data on objects in the application. The application gets updated when new objects appear and requests the task runs. My .net 4 logic had a class based on the event-based pattern and had an instance of the class declared (Lets call it methodasync) So when a new object is detected it calls methodasync.IsTaskRunning(taskID). It not it runs the task but if it is running it marks a bool that says it needs to run again. When the methodasync completes it checks that bool and if "True" it runs again.
    – Oli
    Aug 23, 2012 at 19:33
  • @Oli What about just making a queue of delegates to schedule - and then running the items in the queue? It seems far more clear than trying to "rerun" the sam eoperation, etc. Aug 23, 2012 at 19:35
  • See below regarding Queues ;-) Although the same method is re run it's working on different objects every time. If a 1000 objects come in at once I don't want 1000 jobs lined up. The next pass would pick up the 1000 objects and work would be complete but I'd be left with 999 jobs left to run for no reason. I've updated my question with the current code I use for clarity.
    – Oli
    Aug 23, 2012 at 19:44
0
SemaphoreSlim queueToAccessQueue = new SemaphoreSlim(1);
object queueLock = new object();
long queuedRequests = 0;
Task _loadingTask;
public void RetrieveItems() {
  lock (queueLock) {
      queuedRequests++;
      if (queuedRequests == 1) { // 1 is the minimum size of the queue before another instance is queued
        _loadingTask = _loadingTask?.ContinueWith(async () => {
          RunTheMethodAgain();
          await queueToAccessQueue.WaitAsync();
          queuedRequests = 0; // indicates that the queue has been cleared;
          queueToAccessQueue.Release()
        }) ?? Task.Run(async () => {
          RunTheMethodAgain();
          await queueToAccessQueue.WaitAsync();
          queuedRequests = 0; // indicates that the queue has been cleared;
          queueToAccessQueue.Release();
        });
      }
  }
}
public void RunTheMethodAgain() {
  ** run the method again **
}

The added bonus is that you can see how many items are sitting in the queue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.