2014-01-24 42 views
0

我有一個應用程序從文件中讀取並在彈出窗口中顯示文件的內容。該文本文件以這種方式包含數據;在C#應用程序中添加暫停以執行

d:\\ ABC \\ xyz.txt將該| xyz.txt將該

d:\\ \\ MP3 boom.mp3 | boom.mp3

現在,應用程序讀取一行從文本文件中以另一種形式顯示行內容,並且這些彈出窗口一次顯示,我想要做的是,如果有多行,則在10秒暫停後顯示每個彈出窗口,但Thread.Sleep(10000 )不適合我。讀取的代碼如下所示。

void FileDetected() 
    { 
     int counter = 0,c=1; 
     string line; 
     System.IO.StreamReader file = new System.IO.StreamReader(FILEPATH); 
     while ((line = file.ReadLine()) != null) 
     { 
      string[] words = line.Split('|'); 
      c = 1; 
      path = ""; fileName = ""; 
      foreach (string word in words) 
      { 
       if (c == 1) 
        path = word.Replace(@"\\", @"\"); 
       if (c==2) 
        fileName = word; 
       c++; 
      } 
      counter++; 
      if (path != "" && fileName != "") 
      { 
       Console.WriteLine("Path :" + path); 
       Console.WriteLine("FileName: " + fileName); 
       popup dlg = new popup(path, fileName); 
       dlg.Show(); 
       //Thread.Sleep(10000); 
      } 
     } 

請親引導我。

+1

有什麼問題? –

+0

我想在10秒後顯示每個彈出窗口不是一次全部顯示 – WiXXeY

+2

Thread.Sleep有什麼問題? –

回答

2

如果您使用.NET 4.5(或4.0與Visual Studio 2012或更新版本,通過NuGet下載Microsoft.Bcl.Async),使用async/await很容易。

//You will likely need to modify the calling code to use async/await too. 
async Task FileDetected() 
{ 
    int counter = 0,c=1; 
    string line; 
    System.IO.StreamReader file = new System.IO.StreamReader(FILEPATH); 
    while ((line = file.ReadLine()) != null) 
    { 
     string[] words = line.Split('|'); 
     c = 1; 
     path = ""; fileName = ""; 
     foreach (string word in words) 
     { 
      if (c == 1) 
       path = word.Replace(@"\\", @"\"); 
      if (c==2) 
       fileName = word; 
      c++; 
     } 
     counter++; 
     if (path != "" && fileName != "") 
     { 
      Console.WriteLine("Path :" + path); 
      Console.WriteLine("FileName: " + fileName); 
      popup dlg = new popup(path, fileName); 
      dlg.Show(); 

      //Pauses the loop for 10 sec but does not lock up the UI. 
      await Task.Delay(10000); 
     } 
    }