简体   繁体   English

接口级隔离

[英]Interface-level isolation

In my console application I have the class that incapsulates performing long-continued work and I need show the progress to user. 在我的控制台应用程序中,我有封装执行长时间连续工作的类,需要向用户显示进度。 Do I need put into object of this class a delegate for interaction with console or to write from class right to screen is ok from the standpoint of application structure? 从应用程序结构的角度来看,我是否需要在此类的对象中放置一个与控制台进行交互的委托或从类向屏幕右写就可以了?

Do not write to the screen from within that class. 不要从该类中写入屏幕。 I would go with your first suggestion to use events for this - not simply delegates. 我会同意您的第一个建议,即为此使用事件-不仅仅是委托。

You could have an event named OnProgressUpdate which informs the main thread about your current progress state. 您可能有一个名为OnProgressUpdate的事件,该事件通知主线程您当前的进度状态。

I prefer creating an interface IProgressToken which allows setting the current progress, and supplying that to the calculation method. 我更喜欢创建一个接口IProgressToken ,该接口允许设置当前进度并将其提供给计算方法。

You can then create an implementation of that interface that writes the progress to the console directly, or every so often, or that updates a progress bar on a form, sending an sms, without having to change the class that performs the calculation. 然后,您可以创建该接口的实现,该实现将进度直接写入控制台,或者每隔一段时间将其写入控制台,或者更新表单上的进度栏,发送短信,而无需更改执行计算的类。

interface IProgressToken
{
    void SetProgress(float percentage);
}

class MyProgressToken : IProgressToken
{
    void SetProgress(float percentage)
    {
        Console.WriteLine("current progress: " + percentage + "%");
    }
}

// The long running method
ResultType MyCalculationMethod(InputType input, IProgressToken progressToken)
{
    progressToken.SetProgress(0);
    ...
    progressToken.SetProgress(100);
}

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

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