简体   繁体   中英

IProgress<T> in .NET 4.0

Is there some older .NET 4.0 equivalent of interface or class of IProgress (which is available only from .NET 4.5) which can be used for sending progress from task to UI?

Or should I write my own class/interface for it?

There are really two parts to IProgress<T> : the interface itself, and the provided implementation, Progress<T> . Technically, the interface doesn't even require cross-thread support, though of course that's how it's used in practice.

The interface, you could just copy verbatim from the documentation for .NET 4.5. It's just a declaration. But for it to be useful, you'll want to implement it as well. For that, you'll need to use SynchronizationContext to handle the cross-thread invocation of the ProgressChanged event or the handler provided to the Progress<T> constructor. You could write the whole thing yourself, but IMHO it's reasonable to just copy/paste from the .NET source code: http://referencesource.microsoft.com/#mscorlib/system/progress.cs,d23df0450d3fd0d6

It's a relatively simple class, and wouldn't be hard to reimplement, but there shouldn't be anything about the actual .NET implementation that requires other 4.5 features, so copy/paste from the source should work fine.

That said, note that the equivalent functionality is in fact available in earlier versions of .NET, in the form of the BackgroundWorker class. This combines both the asynchronous execution that is typically used alongside IProgress<T> with the ProgressChanged event that allows the asynchronous operation to report progress. Since there's only one .NET version before 4.5 that also includes the TPL support that is typically used with IProgress<T> , using BackgroundWorker probably makes more sense in the context of pre-4.5 legacy code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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