本文整理汇总了C#中IProgress.?.Report方法的典型用法代码示例。如果您正苦于以下问题:C# IProgress.?.Report方法的具体用法?C# IProgress.?.Report怎么用?C# IProgress.?.Report使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IProgress
的用法示例。
在下文中一共展示了IProgress.?.Report方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DownloadFileAsync
public static async Task DownloadFileAsync(this HttpClient client, Uri url, Stream output, IProgress<double> progress)
{
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
if (!response.IsSuccessStatusCode)
{
throw new Exception($"The request returned with HTTP status code {response.StatusCode}");
}
var total = response.Content.Headers.ContentLength ?? -1L;
using (var stream = await response.Content.ReadAsStreamAsync())
{
var totalRead = 0L;
var buffer = new byte[81920]; // Default size from .NET docs on CopyTo
while (true)
{
var read = await stream.ReadAsync(buffer, 0, buffer.Length);
if (read == 0)
{
break;
}
await output.WriteAsync(buffer, 0, read);
totalRead += read;
// Can't report progress if there was no Content-Length
if (total > 0)
{
progress?.Report(totalRead * 1d / (total * 1d) * 100);
}
}
progress?.Report(100);
}
}
}
示例2: ExportFbxWithIniAsync
public async Task ExportFbxWithIniAsync(string fbxFilename, IProgress<string> progress = null, CancellationToken cancellation = default(CancellationToken)) {
var colladaFilename = fbxFilename + ".dae";
progress?.Report("Exporting to Collada format…");
await Task.Run(() => ExportCollada(colladaFilename), cancellation);
if (cancellation.IsCancellationRequested) return;
progress?.Report("Convert Collada to FBX…");
await Task.Run(() => ConvertColladaToFbx(colladaFilename, fbxFilename), cancellation);
if (cancellation.IsCancellationRequested) return;
progress?.Report("Saving INI-file…");
await Task.Run(() => ExportIni(fbxFilename + ".ini", Path.GetFileName(fbxFilename)), cancellation);
}
示例3: LoadAsyncTo
public static async Task<string> LoadAsyncTo(string argument, string destination, IProgress<AsyncProgressEntry> progress = null,
CancellationToken cancellation = default(CancellationToken)) {
var loader = CreateLoader(argument);
try {
// TODO: Timeout?
using (var client = new CookieAwareWebClient {
Headers = {
[HttpRequestHeader.UserAgent] = CmApiProvider.UserAgent
}
}) {
progress?.Report(AsyncProgressEntry.Indetermitate);
cancellation.ThrowIfCancellationRequested();
cancellation.Register(client.CancelAsync);
if (!await loader.PrepareAsync(client, cancellation) ||
cancellation.IsCancellationRequested) return null;
var skipEvent = 0;
client.DownloadProgressChanged += (sender, args) => {
if (++skipEvent > 50) {
skipEvent = 0;
} else {
return;
}
var total = args.TotalBytesToReceive;
if (total == -1 && loader.TotalSize != -1) {
total = Math.Max(loader.TotalSize, args.BytesReceived);
}
// ReSharper disable once AccessToDisposedClosure
progress?.Report(AsyncProgressEntry.CreateDownloading(args.BytesReceived, total));
};
await loader.DownloadAsync(client, destination, cancellation);
if (cancellation.IsCancellationRequested) return null;
Logging.Debug("Loaded: " + destination);
}
return destination;
} catch (TaskCanceledException) {
return null;
} catch (Exception e) {
NonfatalError.Notify(ToolsStrings.Common_CannotDownloadFile, ToolsStrings.Common_CannotDownloadFile_Commentary, e);
return null;
}
}
示例4: 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);
}
}
示例5: ExecuteBatchWithoutJournalAsync
public static async Task ExecuteBatchWithoutJournalAsync(this SqliteConnection connection, string query, IEnumerable<object[]> parameterSeries, int batchSize, IProgress<int> progress = null)
{
foreach (var batchedParameterSeries in parameterSeries.Batch(batchSize))
{
await connection.ExecuteBatchWithoutJournalAsync(query, batchedParameterSeries).ConfigureAwait(false);
progress?.Report(batchedParameterSeries.Count());
}
}
示例6: Run
public async Task Run(IEnumerable<IAcError> errors, IProgress<AsyncProgressEntry> progress, CancellationToken cancellation) {
var list = errors.ToList();
for (var i = 0; i < list.Count; i++) {
var error = list[i];
progress?.Report(new AsyncProgressEntry(error.Target.DisplayName, (double)i / list.Count));
await base.Run(error, progress, cancellation);
if (cancellation.IsCancellationRequested) return;
await Task.Delay(10, cancellation);
if (cancellation.IsCancellationRequested) return;
}
}
示例7: CopyToAsync
public static async Task CopyToAsync(this Stream source, Stream destination, IProgress<long> progress, CancellationToken cancellationToken) {
byte[] buffer = new byte[81920];
int bytesRead = 0;
long bytesTotal = 0;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) > 0) {
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken);
bytesTotal += bytesRead;
progress?.Report(bytesTotal);
}
await destination.FlushAsync(cancellationToken);
}
示例8: CopyToAsync
public static async Task CopyToAsync(this Stream source, Stream destination, IProgress<long> progress, int bufferSize = 81920, CancellationToken cancellationToken = default(CancellationToken))
{
byte[] buffer = new byte[bufferSize];
int bytesRead;
long bytesCopied = 0;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
bytesCopied += bytesRead;
progress?.Report(bytesCopied);
}
}
示例9: ParseIPRangesAsync
private async Task<IEnumerable<IPRangeLocation>> ParseIPRangesAsync(Stream stream, Dictionary<int, CityLocation> citiesLocationsDict, IProgress<int> progress)
{
List<IPRangeLocation> locations = new List<IPRangeLocation>();
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var range = await ParseIPRangeAsync(reader.ReadLine(), citiesLocationsDict);
if (range != null)
{
locations.Add(range);
progress?.Report(1);
}
}
}
return locations;
}
示例10: ScrapePageAsync
protected async Task <Page> ScrapePageAsync (LinkItem link, string hRefXPath, string imageXPath, Uri host, IProgress <IProgressReportable> progress)
{
var document = new HtmlDocument ();
try
{
using (var client = new WebClient ()) document.LoadHtml (await client.DownloadStringTaskAsync (new Uri (link.HRef)));
}
catch (WebException)
{
return null;
}
var linkItems = ScrapeLinkItems (document.DocumentNode.SelectNodes (hRefXPath), host);
var imageItems = ScrapeImageItems (document.DocumentNode.SelectNodes (imageXPath), host);
QueueLinksForScraping (linkItems);
progress?.Report (new PageProgressReport (finishedLinkItems.Count, Interlocked.Read (ref totalLinkItems)));
return new Page (linkItems, imageItems);
}
示例11: RenameFiles
public void RenameFiles(IList<FileWrapper> files, TimeSpan timeOffset, string constantName, IProgress<double> progress)
{
DoAbort = false;
for (var i = 0; (i < files.Count) && !DoAbort; i++)
{
var file = files[i];
var directory = Path.GetDirectoryName(file.FullName);
if (file.CreatedTime == null)
{
file.CreatedTime = _fileMetaDataService.GetExifTime(file.FullName);
}
var newFileName = CalculateNewFileName(file.CreatedTime, i, files.Count, timeOffset, constantName);
var newFullName = Path.Combine(directory ?? string.Empty, newFileName);
_fileSystemService.RenameFile(file, newFullName, files);
progress?.Report((i + 1.0) / files.Count);
}
}
示例12: CopyTo
public override async Task CopyTo(DirectoryViewModel targetDirectory, CancellationToken ct, IProgress<double> progress)
{
var resultFileSystemFullName = Path.Combine(targetDirectory.FullName, this.Name);
using (FileStream sourceStream =
new FileStream(this.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, useAsync: true))
using (FileStream targetStream =
new FileStream(resultFileSystemFullName, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, useAsync: true))
{
double totalBytesRead = 0;
byte[] buffer = new byte[BufferSize];
int bytesRead = 0;
while ((bytesRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length, ct)) != 0)
{
totalBytesRead += bytesRead;
await targetStream.WriteAsync(buffer, 0, bytesRead, ct);
progress?.Report(totalBytesRead / sourceStream.Length);
}
}
}
示例13: InstallCustom
public async Task<string> InstallCustom(string id, IProgress<double?> progress = null, CancellationToken cancellation = default(CancellationToken)) {
var destination = FilesStorage.Instance.GetDirectory("Locales", id);
var data = await CmApiProvider.GetDataAsync(@"locales/get/base", progress, cancellation);
if (cancellation.IsCancellationRequested || data == null) return null;
progress?.Report(null);
using (var memory = new MemoryStream(data))
using (var updateZip = new ZipArchive(memory)) {
foreach (var entry in updateZip.Entries) {
using (var stream = entry.Open()) {
var filename = Path.Combine(destination, entry.Name);
if (File.Exists(filename)) continue;
await FileUtils.WriteAllBytesAsync(filename, stream, cancellation);
if (cancellation.IsCancellationRequested) return null;
}
}
}
return destination;
}
示例14: AwaitableTransferRequest
public AwaitableTransferRequest(BackgroundTransferRequest request, IProgress<ProgressValue> progress)
{
_request = request;
_tcs = new TaskCompletionSource<object>();
Observable.FromEventPattern<BackgroundTransferEventArgs>(
h => request.TransferProgressChanged += h,
h => request.TransferProgressChanged -= h)
.Select(args => args.EventArgs.Request)
.Subscribe(r =>
{
//TODO: handle uploading BytesSent (should be handled on higher level in Wrapper.ToUpload())
var progressValue = new ProgressValue((ulong) r.BytesReceived, (ulong) r.TotalBytesToReceive);
this.Log().Debug("{0}: current {1}, total {2}", Path.GetFileName(r.RequestUri.OriginalString), progressValue.Current, progressValue.Total);
progress?.Report(progressValue);
});
Observable.FromEventPattern<BackgroundTransferEventArgs>(
h => request.TransferStatusChanged += h,
h => request.TransferStatusChanged -= h)
.Select(p => p.EventArgs.Request)
.StartWith(request)
.Distinct(r => r.TransferStatus)
.Subscribe(req =>
{
if (req.TransferStatus == TransferStatus.Completed)
{
if (req.TransferError != null)
_tcs.SetException(req.TransferError);
else
_tcs.SetResult(null);
}
else if (req.TransferStatus == TransferStatus.Unknown)
{
_tcs.SetException(new TransferStatusUnknownException());
}
});
}
示例15: CreateAndSaveCarsAsync
public static async Task<string> CreateAndSaveCarsAsync(int carsCount, IProgress<int> progress = null)
{
Stopwatch watch = new Stopwatch();
//watch.Start();
await Task.Run(() =>
{
using(var saveSession = sessionFactory.OpenStatelessSession())
using (var transaction = saveSession.BeginTransaction())
{
watch.Start();
var random = new Random();
IList<Manufacturer> manufacturers = GetManufacturers();
for (int current = 0; current < carsCount; current++)
{
Car carEntity = CreateNewCar(random, manufacturers, current);
saveSession.Insert(carEntity);
progress?.Report((int)(((float)current / carsCount) * 100));
}
//watch.Start();
transaction.Commit();
watch.Stop();
}
});
//watch.Stop();
//session.FlushMode = FlushMode.Auto;
return watch.ElapsedMilliseconds.ToString();
}