C# 进步<;T>;不';我没有报告功能
我有windows窗体应用程序这是我的代码:C# 进步<;T>;不';我没有报告功能,c#,winforms,async-await,C#,Winforms,Async Await,我有windows窗体应用程序这是我的代码: private async void btnGo_Click(object sender, EventArgs e) { Progress<string> labelVal = new Progress<string>(a => labelValue.Text = a); Progress<int> progressPercentage = new Progress
private async void btnGo_Click(object sender, EventArgs e)
{
Progress<string> labelVal = new Progress<string>(a => labelValue.Text = a);
Progress<int> progressPercentage = new Progress<int>(b => progressBar1.Value = b);
// MakeActionAsync(labelVal, progressPercentage);
await Task.Factory.StartNew(()=>MakeActionAsync(labelVal,progressPercentage));
MessageBox.Show("Action completed");
}
private void MakeActionAsync(Progress<string> labelVal, Progress<int> progressPercentage)
{
int numberOfIterations=1000;
for(int i=0;i<numberOfIterations;i++)
{
Thread.Sleep(10);
labelVal.Report(i.ToString());
progressPercentage.Report(i*100/numberOfIterations+1);
}
}
private async void btnGo\u单击(对象发送方,事件参数e)
{
Progress labelVal=新进度(a=>labelValue.Text=a);
进度百分比=新进度(b=>progressBar1.Value=b);
//MakeActionAsync(labelVal,progressPercentage);
wait Task.Factory.StartNew(()=>MakeActionAsync(labelVal,progressPercentage));
MessageBox.Show(“操作已完成”);
}
私有void MakeActionAsync(进度标签、进度百分比)
{
int numberOfIterations=1000;
对于(int i=0;iProgress
使用实现了该方法。因此,您无法使用类型为Progress
的实例访问Report
方法。您需要将其强制转换为IProgress
以使用Report
只需将声明更改为IProgress
iprogressprogresspercentage=新进度(b=>progressBar1.Value=b);
或者用石膏
((IProgress<int>)progressPercentage).Report(i*100/numberOfIterations+1);
((IProgress)进度百分比)。报告(i*100/numberOfIterations+1);
我更喜欢前一个版本,后一个版本比较笨拙。如中所示,该方法是使用显式接口实现实现的。这意味着如果不使用接口访问该方法,则该方法是隐藏的
显式接口实现用于在引用接口时使某些属性和方法可见,但在任何派生类中都不可见。因此,只有在使用IProgress
作为变量类型时,才能“看到”它们,而在使用Progress
时则不能
试试这个:
((IProgress<string>)progressPercentage).Report(i*100/numberOfIterations+1);
((IProgress)进度百分比)。报告(i*100/numberOfIterations+1);
或者,当您只需要引用接口声明中可用的属性和方法时:
IProgress<string> progressPercentage = ...;
progressPercentage.Report(i*100/numberOfIterations+1);
IProgress progressPercentage=。。。;
进度百分比报告(i*100/迭代次数+1);
您所说的“显式接口实现”是什么意思?接口方法不应该在子类中可见?
((IProgress<int>)progressPercentage).Report(i*100/numberOfIterations+1);
((IProgress<string>)progressPercentage).Report(i*100/numberOfIterations+1);
IProgress<string> progressPercentage = ...;
progressPercentage.Report(i*100/numberOfIterations+1);