We know that asynchronous operations in Metro C ++ require developers to use tasks and then to implement them, unlike await in C #, the next sentence is executed only after the current asynchronous execution is complete.
Recently, thread conflicts often occur when saving and writing the content of a file to another file. For example, if you write the content of file a to file B, delete file, this operation involves the following steps:
(1) Open File B and initialize the datawriter object through the file stream.
(2) Open File A and initialize the datareader object through the file stream.
(3) load the content of file a through the datareader object
(4) write content through datawriter
(5) Save datawriter
(6) datawriter refresh
Each step above must be integrated. If the current operations on files A and B are not completed completely, and operations on these files are performed on other threads, thread conflicts often occur.
The following provides a simple example of the above steps: Task <irandomaccessstream ^> (storagefileb-> openasync (fileaccessmode: readwrite ))
. Then ([this] (irandomaccessstream ^ rastream)
{
Ioutputstream ^ outstream = rastream-> getoutputstreamat (0 );
Datawriter ^ bbrw = ref new datawriter (outstream );
Task <irandomaccessstream ^> (storagefilea-> openasync (fileaccessmode: Read ))
. Then ([bbrw, this] (irandomaccessstream ^ readstream)
{
Datareader ^ datareader = ref new datareader (readstream );
Task <unsigned int> (datareader-> loadasync (unsigned INT) readstream-> size). Then ([This, bbrw, datareader] (unsigned int numbytesloaded)
{
Array <unsigned char, 1> ^ filecontent = ref new array <unsigned char, 1> (numbytesloaded );
Datareader-> readbytes (filecontent );
Bbrw-> writebytes (filecontent );
Task <unsigned int> store (bbrw-> storeasync ());
Store. Then ([bbrw] (unsigned INT)
{
Return bbrw-> flushasync ();
}). Then ([=] (bool flushsucceeded)
{
Bbrw-> detachstream (); do anything ....
});
});
});
});
The last bbrw-> detachstream () is very important. It is used to separate the stream associated with datawriter. If we do not separate the stream, it will be prone to conflict when we operate the file stream again.
If the same file is stored in the project multiple times, make sure that you do not operate on the same file at the same time. Otherwise, thread conflicts may easily occur. If you want to operate the same file in different modules, you can use semaphores.