簡體   English   中英

如何在不等待C#中調用函數完成的情況下繼續執行函數

[英]how to continue a function without waiting for completion of called function in C#

我的代碼中有一個調度程序函數,該函數在某個特定時間調用另一個函數,如下所示:

private void timer_startTimer_Tick(object sender, EventArgs e)
    {
        Target10 currentTime = this;
        currentTime.CurrentTime = currentTime.CurrentTime - 1;
        this.txttimer.Text = string.Concat("0 : ", Convert.ToString(this.CurrentTime));
        if(CurrentTime == 0)
            timer_startTimer.Stop();
        if (CuurentTime == 10)
        {
            getResult();
        }

    }

如上面的代碼所述,我的函數timer_startTimer_Tick將在10秒鍾調用函數getResult 函數getResult()將需要一些時間才能完成。 如何在不等待getResult函數完成的情況下繼續執行我的父函數timer_startTimer_Tick

將方法調用包裝在任務中。

Task.Run(() => getResult());

您可以使用Threads對象來完成這項工作。

限定:

private Thread thread;
private Queue<Action> queue; // The Action Queue

將上面的代碼放入類構造函數中:

 thread = new Thread(new ThreadStart(delegate {
     while (true)
     {
         if (queue.Count > 0)
             queue.Dequeue()(); //This command takes the function of the queue and executes it
     }
 }));
 queue = new Queue<Action>(); // Instanciate the queue
 thread.Start();

在他的計時器中,而不是調用函數,而是將其放在隊列中:

...
if (CuurentTime == 10)
{
    queue.Enqueue(getResult); //no parenthesis
}
...

或者,您可以使用異步方法。 看一下這些站點:

http://www.dotnetperls.com/async

http://www.codeproject.com/Tips/591586/Asynchronous-Programming-in-Csharp-using-async

真誠地建議您了解異步方法的解決方案

您可以使用Task (導入System.Threading.Task)或異步/等待模式的某些實現。 最簡單的方法是Task.Run(() => getResult()); 它將在后台啟動getResult()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM