2017-03-17 150 views
0

无限循环出于某种原因,我的程序退出与延迟C#

The program '[11632] Kiosk2.vshost.exe' has exited with code 0 (0x0). 

出于此:

public async void Update() 
{ 
    short cooldown = 0; 
    Console.WriteLine("Update function"); 
    do 
    { 
     if (secretKey >= 3 && cooldown == 0) 
     { 
      MessageBox.Show(getGUID(), "Kiosk ID"); 
      cooldown = 9; 
     } 

     if (cooldown > 0) 
      cooldown--; 

     if (secretKey > 0) 
      secretKey--; 

     await Task.Delay(2000); 
    } while (true); 
} 

“更新功能” 的WriteLine被调用。在此处,它被最初叫功能:

public Kiosk() 
{ 
    Init(); 
    Update(); 
    hook(); 

    // _urlRequestWorker = new Thread(Update); 
    // _urlRequestWorker.Start(); 
} 

主要功能

[STAThread] 
static void Main() 
{ 
    bool exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1; 
    if (!exists) 
    { 
     Kiosk k = new Kiosk(); 
    } 
    else 
    { 
     MessageBox.Show("One instance of Kiosk is already running"); 
     Logs.saveLogs("Couldn't start instance of Kiosk because it's already running"); 
     Environment.Exit(0); 
    } 
} 

我不知道为什么会自动退出,我可以用Thread.Sleep,但我想挂接键盘的按键侦听给我看一个消息框。

+2

您有同步调用异步方法。您是否尝试调试 – FCin

+0

? –

+1

Update()。Wait(); –

回答

4

您对Update()的调用未被阻止:您正在开始呼叫,但您仍然需要等待。

删除调用从构造函数,然后更新()...

Kiosk k = new Kiosk(); 
k.Update().GetAwaiter().GetResult(); 

顺便说一句,你真的应该通过命名互斥对象执行单个实例:你已经使用ISN的方法没有保证工作。

+0

除了你的命名互斥体,我在[代码审查](http://codereview.stackexchange.com/questions/156020/an-improved-single-instancing-library)上有一个实现, – TheLethalCoder

0

好吧,所以这个问题得到了解决

 public Kiosk() 
    { 
     Init(); 
     hook(); 
     var updateTask = Update(); 
     updateTask.Wait(); 
    } 




     public async Task Update() 
     {   
     do 
     { 
      //CODE HERE 
      await Task.Delay(5000); 
     } while (true); 
     }