how do set a timeout for a method

前端 未结 8 1310
情书的邮戳
情书的邮戳 2020-12-25 15:10

how do set a timeout for a busy method +C#.

8条回答
  •  暖寄归人
    2020-12-25 15:51

    While MojoFilter's answer is nice it can lead to leaks if the "LongMethod" freezes. You should ABORT the operation if you're not interested in the result anymore.

    public void LongMethod()
    {
        //do stuff
    }
    
    public void ImpatientMethod()
    {
        Action longMethod = LongMethod; //use Func if you need a return value
    
        ManualResetEvent mre = new ManualResetEvent(false);
    
        Thread actionThread = new Thread(new ThreadStart(() =>
        {
            var iar = longMethod.BeginInvoke(null, null);
            longMethod.EndInvoke(iar); //always call endinvoke
            mre.Set();
        }));
    
        actionThread.Start();
        mre.WaitOne(30000); // waiting 30 secs (or less)
        if (actionThread.IsAlive) actionThread.Abort();
    }
    

提交回复
热议问题