本文整理汇总了C#中IProgress类的典型用法代码示例。如果您正苦于以下问题:C# IProgress类的具体用法?C# IProgress怎么用?C# IProgress使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
IProgress类属于命名空间,在下文中一共展示了IProgress类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Run
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
{
var users = _userManager.Users
.DistinctBy(ChannelDownloadScheduledTask.GetUserDistinctValue)
.Select(i => i.Id.ToString("N"))
.ToList();
var numComplete = 0;
foreach (var user in users)
{
double percentPerUser = 1;
percentPerUser /= users.Count;
var startingPercent = numComplete * percentPerUser * 100;
var innerProgress = new ActionableProgress<double>();
innerProgress.RegisterAction(p => progress.Report(startingPercent + (percentPerUser * p)));
await DownloadContent(user, cancellationToken, innerProgress).ConfigureAwait(false);
numComplete++;
double percent = numComplete;
percent /= users.Count;
progress.Report(percent * 100);
}
progress.Report(100);
}
开发者ID:jrags56,项目名称:MediaBrowser,代码行数:28,代码来源:ChannelPostScanTask.cs
示例2: UploadMessageAsync
/// <inheritdoc/>
public async Task<Uri> UploadMessageAsync(Stream content, DateTime expirationUtc, string contentType, string contentEncoding, IProgress<int> bytesCopiedProgress, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(content, "content");
Requires.Range(expirationUtc > DateTime.UtcNow, "expirationUtc");
string blobName = Utilities.CreateRandomWebSafeName(DesktopUtilities.BlobNameLength);
if (expirationUtc < DateTime.MaxValue)
{
DateTime roundedUp = expirationUtc - expirationUtc.TimeOfDay + TimeSpan.FromDays(1);
blobName = roundedUp.ToString("yyyy.MM.dd") + "/" + blobName;
}
var blob = this.container.GetBlockBlobReference(blobName);
// Set metadata with the precise expiration time, although for efficiency we also put the blob into a directory
// for efficient deletion based on approximate expiration date.
if (expirationUtc < DateTime.MaxValue)
{
blob.Metadata["DeleteAfter"] = expirationUtc.ToString(CultureInfo.InvariantCulture);
}
blob.Properties.ContentType = contentType;
blob.Properties.ContentEncoding = contentEncoding;
await blob.UploadFromStreamAsync(content.ReadStreamWithProgress(bytesCopiedProgress), cancellationToken);
return blob.Uri;
}
开发者ID:AArnott,项目名称:IronPigeon,代码行数:28,代码来源:AzureBlobStorage.cs
示例3: InstallPackage
public async Task InstallPackage(IProgress<double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
{
// Target based on if it is an archive or single assembly
// zip archives are assumed to contain directory structures relative to our ProgramDataPath
var isArchive = string.Equals(Path.GetExtension(package.targetFilename), ".zip", StringComparison.OrdinalIgnoreCase);
var target = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);
// Download to temporary file so that, if interrupted, it won't destroy the existing installation
var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
{
Url = package.sourceUrl,
CancellationToken = cancellationToken,
Progress = progress
}).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
// Validate with a checksum
if (package.checksum != Guid.Empty) // support for legacy uploads for now
{
using (var crypto = new MD5CryptoServiceProvider())
using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
{
var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
if (check != package.checksum)
{
throw new ApplicationException(string.Format("Download validation failed for {0}. Probably corrupted during transfer.", package.name));
}
}
}
cancellationToken.ThrowIfCancellationRequested();
// Success - move it to the real target
try
{
File.Copy(tempFile, target, true);
//If it is an archive - write out a version file so we know what it is
if (isArchive)
{
File.WriteAllText(target+".ver", package.versionStr);
}
}
catch (IOException e)
{
_logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
throw;
}
try
{
File.Delete(tempFile);
}
catch (IOException e)
{
// Don't fail because of this
_logger.ErrorException("Error deleting temp file {0]", e, tempFile);
}
}
开发者ID:snap608,项目名称:MediaBrowser,代码行数:60,代码来源:PackageManager.cs
示例4: PushHumptyOffTheWall
internal static void PushHumptyOffTheWall(IProgress progress, bool writeVerbose, string mainFilePathname)
{
Guard.AgainstNull(progress, "progress");
FileWriterService.CheckFilename(mainFilePathname);
var rootDirectoryName = Path.GetDirectoryName(mainFilePathname);
// NB: This is strictly an ordered list of method calls.
// Don't even 'think' of changing any of them.
CheckForUserCancelRequested(progress);
DeleteOldFiles(rootDirectoryName);
CheckForUserCancelRequested(progress);
WriteVersionFile(mainFilePathname);
// Outer Dict has the class name for its key and a sorted (by guid) dictionary as its value.
// The inner dictionary has a caseless guid as the key and the byte array as the value.
// (Only has current concrete classes.)
var classData = GenerateBasicClassData();
var wellUsedElements = new Dictionary<string, XElement>
{
{SharedConstants.LangProject, null},
{SharedConstants.LexDb, null}
};
var guidToClassMapping = WriteOrCacheProperties(mainFilePathname, classData, wellUsedElements);
CheckForUserCancelRequested(progress);
BaseDomainServices.PushHumptyOffTheWall(progress, writeVerbose, rootDirectoryName, wellUsedElements, classData, guidToClassMapping);
#if DEBUG
// Enable ONLY for testing a round trip.
// FLExProjectUnifier.PutHumptyTogetherAgain(progress, writeVerbose, mainFilePathname);
#endif
}
开发者ID:gmartin7,项目名称:flexbridge,代码行数:30,代码来源:FLExProjectSplitter.cs
示例5: SyncInternal
private async Task SyncInternal(ServerInfo server, IProgress<double> progress, CancellationToken cancellationToken)
{
_logger.Debug("Beginning ServerSync with server {0}, Id {1}", server.Name, server.Id);
if (string.IsNullOrWhiteSpace(server.AccessToken) && string.IsNullOrWhiteSpace(server.ExchangeToken))
{
_logger.Info("Skipping sync process for server " + server.Name + ". No server authentication information available.");
progress.Report(100);
return;
}
// Don't need these here
var result = await _connectionManager.Connect(server, new ConnectionOptions
{
EnableWebSocket = false,
ReportCapabilities = false,
UpdateDateLastAccessed = false
}, cancellationToken).ConfigureAwait(false);
if (result.State == ConnectionState.SignedIn)
{
await SyncInternal(server, result.ApiClient, progress, cancellationToken).ConfigureAwait(false);
progress.Report(100);
}
else
{
_logger.Info("Skipping sync process for server " + server.Name + ". ConnectionManager returned a state of {0}", result.State.ToString());
progress.Report(100);
}
}
开发者ID:daltekkie,项目名称:Emby.ApiClient,代码行数:31,代码来源:ServerSync.cs
示例6: Run
/// <summary>
/// Runs the specified progress.
/// </summary>
/// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
{
var allSongs = _libraryManager.RootFolder
.GetRecursiveChildren(i => !i.IsFolder && (i is IHasArtist))
.Cast<IHasArtist>()
.ToList();
var allArtists = _libraryManager.GetArtists(allSongs).ToList();
var numComplete = 0;
var numArtists = allArtists.Count;
foreach (var artistItem in allArtists)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
catch (IOException ex)
{
_logger.ErrorException("Error validating Artist {0}", ex, artistItem.Name);
}
// Update progress
numComplete++;
double percent = numComplete;
percent /= numArtists;
progress.Report(100 * percent);
}
}
开发者ID:rezafouladian,项目名称:Emby,代码行数:39,代码来源:ArtistsValidator.cs
示例7: LoadEmployees
private DataResult<IList<Employee>> LoadEmployees(CancellationToken token, IProgress<double> progress)
{
var employees = XDocument.Load(@"data\sampledata.xml")
.Descendants("Employee")
.Select(x => new Employee {
Number = int.Parse(x.Descendants("Number").First().Value),
Name = x.Descendants("Name").First().Value,
Surname = x.Descendants("Surname").First().Value,
Salary = double.Parse(x.Descendants("Salary").First().Value)
})
.ToList();
var itemIndex = 0;
var result = new DataResult<IList<Employee>> {
Result = new List<Employee>()
};
try {
foreach (var employee in employees) {
Thread.CurrentThread.Join(100);
result.Result.Add(employee);
token.ThrowIfCancellationRequested();
progress.Report((++itemIndex*100)/employees.Count);
}
}
catch (OperationCanceledException ex) {
result.Exception = ex;
}
return result;
}
开发者ID:spudcz,项目名称:WpfAsyncData,代码行数:31,代码来源:EmployeeDataProvider.cs
示例8: FillDataTo
protected override async Task FillDataTo(System.Net.WebRequest webrqst, CancellationToken cancellationToken, IProgress<ProgressReport> progress)
{
progress.ReportWhenNotNull(() => ProgressReport
.CreateNew(RequestResponseSteps
.Requesting_N_Uploading, 0, 1));
var qd = System.Text.Encoding.UTF8.GetBytes(JsonClientHelper.GetQueryData(RequestData.PostFieldValues));
webrqst.ContentType = "application/x-www-form-urlencoded";
#if SILVERLIGHT_4||SILVERLIGHT_5||DOTNET45
webrqst.ContentLength = qd.Length;
#endif
var rqstStrm = await webrqst.GetRequestStreamAsync().ConfigureAwait(false);
await rqstStrm.WriteAsync(qd, 0, qd.Length).ConfigureAwait(false);
progress.ReportWhenNotNull(() => ProgressReport
.CreateNew(RequestResponseSteps
.Requesting_N_Uploading, 1, 1));
}
开发者ID:JDCB,项目名称:JDCB,代码行数:25,代码来源:PostRequest.cs
示例9: ExportTexturesAsync
public async Task ExportTexturesAsync(string textureDir, IProgress<string> progress = null, CancellationToken cancellation = default(CancellationToken)) {
foreach (var texture in Textures.Values) {
if (cancellation.IsCancellationRequested) return;
progress?.Report(texture.Name);
await FileUtils.WriteAllBytesAsync(Path.Combine(textureDir, texture.Name), TexturesData[texture.Name], cancellation);
}
}
开发者ID:gro-ove,项目名称:actools,代码行数:7,代码来源:Kn5_ExportTextures.cs
示例10: Execute
/// <summary>
///
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="progress"></param>
/// <returns></returns>
public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
var users = _userManager.Users.Where(u => UserHelper.GetTraktUser(u) != null).ToList();
// No point going further if we don't have users.
if (users.Count == 0)
{
_logger.Info("No Users returned");
return;
}
// purely for progress reporting
var percentPerUser = 100 / users.Count;
double currentProgress = 0;
var numComplete = 0;
foreach (var user in users)
{
try
{
await SyncTraktDataForUser(user, currentProgress, cancellationToken, progress, percentPerUser).ConfigureAwait(false);
numComplete++;
currentProgress = percentPerUser * numComplete;
progress.Report(currentProgress);
}
catch (Exception ex)
{
_logger.ErrorException("Error syncing trakt data for user {0}", ex, user.Name);
}
}
}
开发者ID:ryu4000,项目名称:MediaBrowser.Plugins,代码行数:38,代码来源:SyncFromTraktTask.cs
示例11: TryMergeEntries
public static bool TryMergeEntries(LexEntry entry1, LexEntry entry2, string[] traitsWithMultiplicity, IProgress progress)
{
if (!entry1.LexicalForm.CanBeUnifiedWith(entry2.LexicalForm))
{
progress.WriteMessageWithColor("gray","Attempting to merge entries, but could not because their Lexical Forms clash in some writing system.");
return false;
}
if (!SenseMerger.TryMergeProperties(entry1, entry2, traitsWithMultiplicity, "entries for "+entry1.ToString(), progress))
return false;
// at this point, we're committed to doing the merge
entry1.LexicalForm.MergeIn(entry2.LexicalForm);
var senses = entry2.Senses.ToArray();
foreach (var sense in senses)
{
MergeOrAddSense(entry1, sense, traitsWithMultiplicity, progress);
}
if (entry2.ModificationTime > entry1.ModificationTime)
{
entry1.ModificationTime = entry2.ModificationTime;
}
entry1.IsDirty = true;
return true;
}
开发者ID:jwickberg,项目名称:libpalaso,代码行数:29,代码来源:EntryMerger.cs
示例12: RunInternal
private void RunInternal(IProgress<double> progress, CancellationToken cancellationToken)
{
var allItems = _libraryManager.RootFolder
.RecursiveChildren
.ToList();
var musicAlbums = allItems
.OfType<MusicAlbum>()
.ToList();
AttachMovieSoundtracks(allItems, musicAlbums, cancellationToken);
progress.Report(25);
AttachTvSoundtracks(allItems, musicAlbums, cancellationToken);
progress.Report(50);
AttachGameSoundtracks(allItems, musicAlbums, cancellationToken);
progress.Report(75);
AttachAlbumLinks(allItems, musicAlbums, cancellationToken);
progress.Report(100);
}
开发者ID:RomanDengin,项目名称:MediaBrowser,代码行数:26,代码来源:SoundtrackPostScanTask.cs
示例13: ExtractImage
private void ExtractImage(List<WriteableBitmap> tempTiles, BitmapSource image, int spacing, int offset, IProgress<ProgressDialogState> progress = null)
{
var sourceImage = BitmapFactory.ConvertToPbgra32Format(image);
var jump = 16 + spacing;
var totalTiles = ((image.PixelWidth - offset) / jump) * ((image.PixelHeight - offset) / jump);
var currentTile = 0;
for (var y = offset; y < image.PixelHeight; y += jump)
{
for (var x = offset; x < image.PixelWidth; x += jump)
{
var tileImage = new WriteableBitmap(16, 16, 96, 96, PixelFormats.Pbgra32, null);
tileImage.Blit(new System.Windows.Rect(0, 0, 16, 16), sourceImage, new System.Windows.Rect(x, y, 16, 16));
tempTiles.Add(tileImage);
currentTile++;
if (progress != null)
{
progress.Report(new ProgressDialogState() {
ProgressPercentage = currentTile * 100 / totalTiles,
Description = string.Format("Extracting {0} / {1}", currentTile, totalTiles)
});
}
}
}
}
开发者ID:Tesserex,项目名称:C--MegaMan-Engine,代码行数:27,代码来源:TilesetImporter.cs
示例14: DoAsync
public Task DoAsync(IProgress<int> Progress)
{
Progress.Report(1);
Thread.Sleep(800);
Progress.Report(95);
return Task.FromResult<object>(null);
}
开发者ID:David-Desmaisons,项目名称:EasyActor,代码行数:7,代码来源:DummyDisposableClass.cs
示例15: Run
/// <summary>
/// Runs the specified progress.
/// </summary>
/// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
{
var files = _libraryManager.GetAllIntroFiles().ToList();
var numComplete = 0;
foreach (var file in files)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
await RefreshIntro(file, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.ErrorException("Error refreshing intro {0}", ex, file);
}
numComplete++;
double percent = numComplete;
percent /= files.Count;
progress.Report(percent * 100);
}
}
开发者ID:bigjohn322,项目名称:MediaBrowser,代码行数:35,代码来源:RefreshIntrosTask.cs
示例16: Generate
/// <summary>
/// </summary>
/// <param name="path"></param>
/// <param name="progress"></param>
/// <returns></returns>
public Task<GenerationResult> Generate(string path, IProgress<ProgressResult> progress)
{
return Task.Run(() => {
var db = Schema.Database;
var content = Resources.selection_builder;
var output = PathUtils.FilePath(path, db.PackageName, db.ProviderFolder + Constants.Util);
content = string.Format(content, db.PackageName, db.ProviderFolder + Constants.Util);
if (progress != null) {
progress.Report(new ProgressResult {
Name = this.GetType().Name,
Value = 1
});
}
return new GenerationResult{
Content = new List<string>{
content
},
Path = new List<string>{
output + "SelectionBuilder.java"
}
};
});
}
开发者ID:Reddmist,项目名称:android-code-generators,代码行数:31,代码来源:SelectionBuilderGenerator.cs
示例17: Put
public virtual Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellation = default(CancellationToken))
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
store.GetOrAdd(key, bytes);
return Task.FromResult(key);
}
开发者ID:freemsly,项目名称:Nine.Storage,代码行数:7,代码来源:MemoryBlobStorage.cs
示例18: Run
/// <summary>
/// Runs the specified progress.
/// </summary>
/// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
{
var names = _itemRepo.GetMusicGenreNames();
var numComplete = 0;
var count = names.Count;
foreach (var name in names)
{
try
{
var item = _libraryManager.GetMusicGenre(name);
await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Don't clutter the log
break;
}
catch (Exception ex)
{
_logger.ErrorException("Error refreshing {0}", ex, name);
}
numComplete++;
double percent = numComplete;
percent /= count;
percent *= 100;
progress.Report(percent);
}
progress.Report(100);
}
开发者ID:7illusions,项目名称:Emby,代码行数:41,代码来源:MusicGenresValidator.cs
示例19: CreateRepositoriesFromFolder
public static IEnumerable<AnnotationRepository> CreateRepositoriesFromFolder(string folderPath, IProgress progress)
{
foreach (var path in GetChorusNotesFilePaths(folderPath))
{
yield return AnnotationRepository.FromFile("id", path, progress);
}
}
开发者ID:regnrand,项目名称:chorus,代码行数:7,代码来源:AnnotationRepository.cs
示例20: GetChildren
public override IEnumerable<ISystemEntry> GetChildren(CancellationToken token, IProgress<double> progress)
{
return ProcessUtility.GetChildProcessIds(this.ProcessId)
.WithCancellation(token)
.Select(id => Process.GetProcessById(id))
.Select(proc => new ProcessSystemEntry(this, proc.Id.ToString(), proc));
}
开发者ID:catwalkagogo,项目名称:Heron,代码行数:7,代码来源:ProcessSystemEntry.cs
注:本文中的IProgress类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论