简体   繁体   English

如何在 c# 中使用异步?

[英]How do I use Async in c#?

I am doing c # form application.我正在做 c # 表格申请。 The application is basically a video converter implementation.该应用程序基本上是一个视频转换器实现。 I have two buttons called convert and conver the stop.我有两个按钮,称为转换和转换停止。 Here's what I want to do;这就是我想做的; I don't want the form to lock itself, even if I click on any of these.我不希望表单自行锁定,即使我单击其中任何一个。 I may cancel the process or close the form at that time.届时我可能会取消该过程或关闭表格。 I need to do async, but I don't know how.我需要做异步,但我不知道怎么做。 I can't use a backgroundworker because I'm basically dealing with big data.我不能使用后台工作人员,因为我基本上是在处理大数据。 He can lock the form more.他可以更多地锁定表格。 Please help.请帮忙。

convert the stop code;转换停止代码;

private void Button7_Click(object sender, EventArgs e)
    {
        var ffmpeg = new NReco.VideoConverter.FFMpegConverter();
        ffmpeg.Stop();
                MessageBox.Show("convert is stopped");
    }

Like this:像这样:

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");
}

Note that the MessageBox.Show will be called after the task has completed but the control will return to the main thread at the await call.请注意,MessageBox.Show 将在任务完成后调用,但控件将在等待调用时返回主线程。 This is what confuses people new to async.这就是让刚接触异步的人感到困惑的地方。

Also note that ordinarily an async function will have a Task or Task<T> return type, but as this is an event handler it has void return type.另请注意,通常异步 function 将具有TaskTask<T>返回类型,但由于这是一个事件处理程序,它具有 void 返回类型。 It is one of the few cases where a void return type is correct for an async function.这是 void 返回类型对于异步 function 正确的少数情况之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM