Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to a synchronize tasks?

Tags:

Say I have an async method which saves to file:

async Task SaveToFileAsync()
{
   var file = await folder.GetFileAsync ( ...)
   var stream = file.OpenFileAsync(...)
   ///etc

}

Now imagine that SaveToFileAsync is called twice simultaneously. This is a problem because you can't write on the same file simultaneously

If this were a regular method, lock() would fix this:

void SaveToFile()
{
   lock(something)
   {
      /// code here
   }
}

However, lock is not allowed in an async method.

Of course, one could call Monitor.Enter() or use a mutex but these objects work with threads, not tasks. Therefore they are not the answer.

So since lock() is not an option, how can synchronize multiple tasks? In particular, what code should I write to ensure that "SaveToFileAsync" is called only once at a time?

like image 577
user380719 Avatar asked Apr 12 '12 17:04

user380719


People also ask

What is task Synchronisation?

In general, a task must synchronize its activity with other tasks to execute a multithreaded program properly. Activity synchronization is also called condition synchronization or sequence control . Activity synchronization ensures that the correct execution order among cooperating tasks is used.

How do I sync a To Do list?

To sync your tasks and lists between your computer and phone, sign in with the same account on each device. Microsoft To Do updates every 5 seconds, so all of your changes should be displayed automatically. Since your tasks are stored on Exchange Online servers, they'll also sync automatically to your Outlook Tasks.

How do you sync tasks in Outlook?

1) Go to "Settings" in PracticePanther. 2) In "Calendar, Tasks & Contacts", enable the sync with Exchange, and enter your Outlook email and password. 3) Set both "Tasks" settings to "Yes". 4) Click "Save".

What is synchronization Informatica?

synchronization. task to synchronize data between a source and a target. For example, you can read sales leads from your sales database and write them into Salesforce. You can also use expressions to transform the data according to your business logic or use data filters to filter data before writing it to targets.


1 Answers

For an async mutual exclusion mechanism, have a look at

    Building Async Coordination Primitives, Part 6: AsyncLock

You could use the AsyncLock class follows:

private readonly AsyncLock m_lock = new AsyncLock();

async Task SaveToFileAsync()
{
    using (await m_lock.LockAsync()) 
    { 
        var file = await folder.GetFileAsync(...);
        var stream = await file.OpenFileAsync(...);
        // etc
    }
}
like image 110
dtb Avatar answered Sep 20 '22 15:09

dtb