C# await async的使用

 

簡單的使用

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("主線程測試開始..");
        AsyncMethod();
        Thread.Sleep(1000);
        Console.WriteLine("主線程測試結束..");
        Console.ReadLine();
    }
 
    static async void AsyncMethod()
    {
        Console.WriteLine("開始異步代碼");
        var result = await MyMethod();
        Console.WriteLine("異步代碼執行完畢");
    }
 
    static async Task<int> MyMethod()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("異步執行" + i.ToString() + "..");
            await Task.Delay(1000); //模擬耗時操作
        }
        return 0;
    }
}

 

等待一個結果

public bool test = false;

void OnGUI()
{
    if(GUI.Button(new Rect(0, 450, 300, 150), "Test"))
    {
        test = true;
    }
}

async void AsyncMethod()
{
    Debug.Log("開始異步代碼");
    await MyMethod();
    Debug.Log("異步代碼執行完畢");
}

async Task MyMethod()
{
    for (int i = 0; i < int.MaxValue; i++)
    {
        await Task.Delay(100);
        Debug.Log("等待...");
        if (test == true)
            break;
    }
    /*await Task.Run(() =>
    {
        while (true)
        {                    
            if (test == true)
            break;
        }
    });
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章