[英]How do I use Async in c#?
我正在做 c # 表格申請。 該應用程序基本上是一個視頻轉換器實現。 我有兩個按鈕,稱為轉換和轉換停止。 這就是我想做的; 我不希望表單自行鎖定,即使我單擊其中任何一個。 屆時我可能會取消該過程或關閉表格。 我需要做異步,但我不知道怎么做。 我不能使用后台工作人員,因為我基本上是在處理大數據。 他可以更多地鎖定表格。 請幫忙。
轉換停止代碼;
private void Button7_Click(object sender, EventArgs e)
{
var ffmpeg = new NReco.VideoConverter.FFMpegConverter();
ffmpeg.Stop();
MessageBox.Show("convert is stopped");
}
像這樣:
private async void Button7_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
//code here that takes a long time. NB nothing that must be run on the main thread
var ffmpeg = new NReco.VideoConverter.FFMpegConverter();
ffmpeg.Stop();
});
//when the above task completes this will then be called on the original thread context (i.e. the main ui thread)
MessageBox.Show("convert is stopped");
}
請注意,MessageBox.Show 將在任務完成后調用,但控件將在等待調用時返回主線程。 這就是讓剛接觸異步的人感到困惑的地方。
另請注意,通常異步 function 將具有Task
或Task<T>
返回類型,但由於這是一個事件處理程序,它具有 void 返回類型。 這是 void 返回類型對於異步 function 正確的少數情況之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.