locked
Dispatcher.BeginInvoke written twice in the same method

    Question

  • Hello, 

    I am working with the accelerometer sensor and I want to write the accelerometer data which the phone is reading into a text file.  In the accelerometer sample on MSDN, there is a line of code which enables the UI to be updated with the latest readings which reads:

    Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading)); 

    The line that I just wrote above is the in the SensorReadingChanged event handler, and what I would like to do is that I would like to know is that if the UI gets updated with the latest accelerometer readings on its own thread, is it possible that I can have another thread which takes the same Accelerometer data readings and writes the readings to a text file?  

    I will appreciate any assistance on this matter. 

    Pranav

    Wednesday, October 8, 2014 7:54 PM

Answers

  • Hi Pranav,

    >is it possible that I can have another thread which takes the same Accelerometer data readings and writes the readings to a text file? 

    Yes, of course. When you success in collecting the accelerometer data in UpdateUI method, you can use Asynchronous programming to open a new thread for writing the data into StorageFile. I would like to share some sample code about how to do it according your previous code.

    Write to StorageFile

     public async Task WriteDataToFileAsync(string fileName, string content)
            {
                byte[] data = Encoding.UTF8.GetBytes(content);
                var folder = ApplicationData.Current.LocalFolder;
                var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                using (var s = await file.OpenStreamForWriteAsync())
                {
                    await s.WriteAsync(data, 0, data.Length);
                }
            }
    

    Read from StorageFile.   

    public async Task<string> ReadFileContentsAsync(string fileName)
            {
                var folder = ApplicationData.Current.LocalFolder;
                try
                {
                    var file = await folder.OpenStreamForReadAsync(fileName);
                    using (var streamReader = new StreamReader(file))
                    {
                        return streamReader.ReadToEnd();
                    }
                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
    

    Use WriteDataToFileAsync method when complete collecting accelerometer data in btnStop_Click event handler.

    //now all data is collecting into the array, write it to local file
                    System.Text.StringBuilder builder = new System.Text.StringBuilder();
                    list.ForEach(f =>
                    {
                        builder.AppendLine(string.Format("Time:{0}, X={1}, Y={2}, Z={3}", f.Time, f.X, f.Y, f.Z));
                    });
                    await WriteDataToFileAsync("data.txt", builder.ToString());
    

    If I misunderstand you, please feel free to let me know.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 9, 2014 6:03 AM
    Moderator

All replies

  • Hi Pranav,

    >is it possible that I can have another thread which takes the same Accelerometer data readings and writes the readings to a text file? 

    Yes, of course. When you success in collecting the accelerometer data in UpdateUI method, you can use Asynchronous programming to open a new thread for writing the data into StorageFile. I would like to share some sample code about how to do it according your previous code.

    Write to StorageFile

     public async Task WriteDataToFileAsync(string fileName, string content)
            {
                byte[] data = Encoding.UTF8.GetBytes(content);
                var folder = ApplicationData.Current.LocalFolder;
                var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                using (var s = await file.OpenStreamForWriteAsync())
                {
                    await s.WriteAsync(data, 0, data.Length);
                }
            }
    

    Read from StorageFile.   

    public async Task<string> ReadFileContentsAsync(string fileName)
            {
                var folder = ApplicationData.Current.LocalFolder;
                try
                {
                    var file = await folder.OpenStreamForReadAsync(fileName);
                    using (var streamReader = new StreamReader(file))
                    {
                        return streamReader.ReadToEnd();
                    }
                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
    

    Use WriteDataToFileAsync method when complete collecting accelerometer data in btnStop_Click event handler.

    //now all data is collecting into the array, write it to local file
                    System.Text.StringBuilder builder = new System.Text.StringBuilder();
                    list.ForEach(f =>
                    {
                        builder.AppendLine(string.Format("Time:{0}, X={1}, Y={2}, Z={3}", f.Time, f.X, f.Y, f.Z));
                    });
                    await WriteDataToFileAsync("data.txt", builder.ToString());
    

    If I misunderstand you, please feel free to let me know.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 9, 2014 6:03 AM
    Moderator
  • Thank you so much Herro!  I really do appreciate the assistance.  However, I do have one more question.  I want to be able to change the title of the text file.  So for example, if I want to have one text file say data-October132014-412.txt, and another text file to have the title data-October132014-530.txt is there a way to do so?  If there is, could you please share some insight on how I may go about doing something like that because I'm using the whole data logging into text file concept for my graduate work.  Therefore, I want to be able to have data which is recorded to be in different files, and if and when I use the ISETool to extract the text files from the app, and I specify the directory on my desktop, the file transfer destination will be overwritten each and every time I transfer a text file from my app to my desktop.  

    Again, thank you very much for the help, and if you could address this one concern regarding the naming of the text files, I will really be glad!

    Regards,

    Monday, October 13, 2014 8:15 PM
  • Hi Pranav,

    > if I want to have one text file say data-October132014-412.txt, and another text file to have the title data-October132014-530.txt is there a way to do so? 

    Yes, of course. We just need to create a method in class to generate the log file title using some algorithms. Note that I don’t know what’s the meaning of the number in the log file (-412.txt, -530.txt), so I use a random number to instead. You should modify that code to meet your requirement. See the following code.

    public class LogFileGenerator
        {
            public static string NextOne()
            {
                string filename = string.Empty;
                Random ran = new Random();
                filename = string.Format("data-{0}-{1}.txt", DateTime.Now.ToString("MMMMddyyyy"), ran.Next(100, 1000));
                return filename;
            }
    }
    

    By the way, if you have new question, I would recommend you post a new thread. If my post is useful, please mark it.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 16, 2014 2:01 AM
    Moderator