簡體   English   中英

異步方法返回類型?

[英]Async method return type?

這是我要嘗試的腳本(使用CodeDomProvider進行編譯和運行)。

AddText("Testing. Press yes to continue.");
var answer = SendYesNo();

if (answer)
{
    AddText("Good.");
    SendOk();
} 
else
{
    AddText("Not good.");
    SendOk();
}

現在。 我希望SendYesNo使用AutoResetEvent,因此它會停止腳本執行,直到給出響應為止。 設置響應后,還將設置自動重置事件,因此它將繼續執行並返回響應。 例如,到目前為止,我有:

public bool SendYesNo()
    {
        this.waitHandle = new AutoResetEvent(false);
        this.waitHandle.WaitOne();

        return this.Selection;
    }

為了設置選擇,我使用:

public void SetSelection(bool selection)
    {
        this.Selection = selection;
        this.waitHandle.Set();
    }

但是,它不起作用(一旦我設置了響應就什么也沒有發生),整個程序被卡住了。 沒有任何功能。 為什么? 我認為我必須為此使用異步,但是我不確定如何使用。 另外,我應該為此使用自定義EventHandler嗎?

謝謝。

可能是如果我明白了,那么您就需要這樣的東西。

private Task<bool> SendYesNo()
{
    if (Yes)
    {
        return true;
    }
    else
    {
        return false;
    }
}

接着

AddText("Testing. Press yes to continue.");
var answer = await SendYesNo();

if (answer)
{
    AddText("Good.");
    SendOk();
} 
else
{
    AddText("Not good.");
    SendOk();
}

這實際上比我想象的要簡單得多。 該框架提供了TaskCompletionSource<T>類型,該類型可以完成您想要的操作。

class NpcScript {

    TaskCompletionSource<bool> response = new TaskCompletionSource<bool> ();

    public void SetResponse(bool value) {
        response.SetResult (value);
    }

    async Task<bool> SendYesNo() {
        return await response.Task;
    }


    public async Task Perform() {
        AddText("Testing. Press yes to continue.");
        var answer = await SendYesNo();

        if (answer)
        {
            AddText("Good.");
            SendOk();
        } 
        else
        {
            AddText("Not good.");
            SendOk();
        }
    }
}

編輯:

您還應該通過await在某些異步上下文中調用Perform。 例如,假設我創建一個任務來處理Perform,另一個任務等待用戶輸入,我可以啟動這兩個任務,但是要等它們全部完成后再繼續在線程中執行。

var script = new NpcScript();

var taskPerform = new Task(async () => {
    await script.Perform();
});
taskPerform.Start();

var taskInput = new Task(() =>
    //get user input here
    script.SetResponse (inp);
});
taskInput.Start();

Task.WaitAll(new Task[] { taskPerform, taskInput });

暫無
暫無

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

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