gpt4 book ai didi

c# - 简化后台 worker 的匿名方法

转载 作者:行者123 更新时间:2023-11-30 19:57:44 24 4
gpt4 key购买 nike

我正在尝试通过单击按钮制作我的所有代码,并在后台工作程序中运行。所以我有以下代码模板。

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
//code
};
backgroundWorker.RunWorkerAsync();
while (backgroundWorker.IsBusy)
{
Application.DoEvents();
}

只是想知道是否有一种方法可以简化这段代码,所以我并没有有效地为我的所有按钮复制相同的代码块。

编辑:我尝试运行的典型代码如下:

//Synchronous task
Wait(2000);
//Synchronous task
return taskResult ? "Success" : "Failure"

最佳答案

没有更多上下文,就不可能提出非常具体的改进建议。也就是说,您肯定可以摆脱 while环形。只需使用:

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
//code
};
backgroundWorker.RunWorkerAsync();

请注意,如果您有要在 BackgroundWorker 时执行的代码任务完成(可能解释为什么你首先有那个 while 循环),这样的事情会起作用(而不是使用你以前有的 while 循环):

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
//code
};
backgroundWorker.RunWorkerCompleted += (sender, e) =>
{
// code to execute when background task is done
};
backgroundWorker.RunWorkerAsync();

在现代 C# 中,BackgroundWorker几乎过时了。它现在提供的主要好处是方便的进度报告,实际上可以通过使用 Progress<T> 轻松获得。 .

如果您不需要报告进度,分解您的代码以使用 async/await很简单:

await Task.Run(() =>
{
//code
});

// code to execute when background task is done

如果您确实需要报告进度,那只会稍微困难一些:

Progress<int> progress = new Progress<int>();

progress.ProgressChanged += (sender, progressValue) =>
{
// do something with "progressValue" here
};

await Task.Run(() =>
{
//code

// When reporting progress ("progressValue" is some hypothetical
// variable containing the progress value to report...Progress<T>
// is generic so you can customize to do whatever you want)
progress.Report(progressValue);
});

// code to execute when background task is done

最后,在某些情况下,您可能需要任务返回一个值。在那种情况下,它看起来更像这样:

var result = await Task.Run(() =>
{
//code

// "someValue" would be a variable or expression having the value you
// want to return. It can be of any type.
return someValue;
});

// At this point in execution "result" now has the value returned by the
// background task. Note that in the above example, the method itself
// is anonymous and so you could just set a local variable at the end of the
// task; the value-returning syntax is more useful when you are calling an
// actual method that itself returns a value, and is especially useful when
// you are calling an `async` method that returns a value (i.e. you're not
// even using `Task.Run()` in the `await` statement.

// code to execute when background task is done

您可以根据需要混合搭配上述技术。

关于c# - 简化后台 worker 的匿名方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28922074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com