none
Read a file within a specified time RRS feed

  • Question

  • Hello,
    I send a request via file.
    After a specified time, I must read the answer and delete this file.
    I make it this way.
    I'm not sure that await, async is right.
    The user input must be operable, but I can only continue the process after an answer.
    Please look here // ####A
        Because of the await is waited, thus a behavior like synchronously, the user interface remains however operable. Do I see that correctly?
    Can you check it out, possibly improve it? Thanks in advance.

    Thanks for tips.
    Greetings Markus
    //Event from a Button.
    private async void FileReadOrTimeout(object sender, RoutedEventArgs e)
    {
    	try
    	{
    	 // ####A
    		var ret = await ReadDataAsync(@"C:\Users\Freitag\Documents\TEST_M_3.xml", 6000);
    		
        	string converted = Encoding.UTF8.GetString(ret, 0, ret.Length);
    		converted = RemoveBom(converted);
    
    		MessageBox.Show(converted + "\n \nEnd");
    	}
    	catch (Exception ex)
    	{
    		MessageBox.Show(ex.Message);
    	}
    }
    
    private async Task<byte[]> ReadDataAsync(string pDatei, int pTimeOutMs)
    {
    	int n = 0;
    	int m = (int)Math.Ceiling(pTimeOutMs / 100.0);
    
    	while (!File.Exists(pDatei))
    	{
    		await Task.Delay(100);
    		n++;
    		if (n == m)
    			throw new FileNotFoundException();
    
    	}
    
    	FileInfo fi = new FileInfo(pDatei);
    	Stream streamXML;
    
    	byte[] data = new byte[fi.Length];
    	using (var fs = fi.OpenRead())
    	{
    		int read = await fs.ReadAsync(data, 0, data.Length);
    		
    		read = data?.Length ?? throw new ArgumentNullException(); // ## Needed?
    
    		streamXML = new MemoryStream(data);
    
    		var gpx = Deserialize<Msg>(streamXML);
    
    		return data;
    	}
    }
    //######################################################

    Monday, December 16, 2019 5:55 PM

All replies

  • https://docs.microsoft.com/en-us/dotnet/api/system.asynccallback?view=netframework-4.8

    You could do a callback.

    Monday, December 16, 2019 7:25 PM
  • Hello,
    What do you think about async and await.
    Would it be any easier and any better?
    Greetings Markus
    Tuesday, December 17, 2019 5:56 PM
  • Hello,
    What do you think about async and await.
    Would it be any easier and any better?
    Greetings Markus

    I have used it in ASP.NET MVC for a responsive UI user experience mainly on HTTPclinet() that is doing async calls to the WebAPI that is doing CRUD with the database using EF.

    Tuesday, December 17, 2019 11:46 PM