我正在尝试在单独的线程上调用的C#类中有一个方法。但是,在开始处理之前,我需要让此函数从用户界面访问多个值,如下所示:
public void validateConnections(bool openExpanderOnError = true) {
//Gather information about the data connection models, and which rows to test
string connectorValue = DBTypes[connector.SelectedValue.ToString()];
EntryRow[] testable = { developer, production, qaTesting, ... , more };
//Run long code
//Churn.....
}
我在上述代码中拥有的变量是通过获取位于同一类中的值来定义的,并且如果它是同步执行的,则可以很好地工作。
但是,为了运行下面的长代码(为简洁起见,我将其裁剪),这些值必须在使用前出现。将我需要的所有信息作为参数传递是不切实际的,因为这很快就会变得难以控制。
如何从UI异步获取这些值?
注意:我尝试对这部分代码使用
Dispatcher.Invoke()
,这导致长代码在设置所需变量之前运行。使用BackgroundWorker
导致长时间运行代码时主线程冻结,这完全违背了第二个线程的目的。编辑1:这是我尝试实现
Dispatcher.Invoke()
方法调用的方式:public void validateConnections(bool openExpanderOnError = true) {
//Gather information about the data connection models, and which rows to test
string connectorValue = "";
EntryRow[] testable = new EntryRow[n];
Dispatcher.Invoke(new Action(() => {
connectorValue = DBTypes[connector.SelectedValue.ToString()];
testable[0] = developer;
testable[1] = production;
//...
testable[n] = qaTesting;
}));
//Run long code
//Churn.....
}
编辑2:最初我叫的是
Dispatcher.BeginInvoke()
,而不是Dispatcher.Invoke()
,它可以正常工作。
最佳答案
您的代码看起来正确。 Dispatcher.Invoke是同步的,因此长代码直到调度的方法完成才开始。也许您之前不小心使用了Dispatcher.BeginInvoke?那是异步版本,它将具有您描述的行为
关于c# - C#任务-从UI异步获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24002729/