本文整理汇总了C#中System.Progress类的典型用法代码示例。如果您正苦于以下问题:C# Progress类的具体用法?C# Progress怎么用?C# Progress使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Progress类属于System命名空间,在下文中一共展示了Progress类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InstallUpdateUninstall
public void InstallUpdateUninstall()
{
var service = GetPackageService();
var progress = new Progress<ProgressMessage>(WriteProgressMessage);
ListModules(service);
service.Install(@"source\TestModule2_v1.0.0.zip", progress);
ListModules(service);
service.Install(@"source\TestModule1_v1.0.0.zip", progress);
ListModules(service);
service.Install(@"source\TestModule2_v1.0.0.zip", progress);
ListModules(service);
service.Update("TestModule2", @"source\TestModule2_v1.1.0.zip", progress);
ListModules(service);
service.Update("TestModule1", @"source\TestModule1_v1.1.0.zip", progress);
ListModules(service);
service.Update("TestModule2", @"source\TestModule2_v1.1.0.zip", progress);
ListModules(service);
service.Uninstall("TestModule1", progress);
ListModules(service);
service.Uninstall("TestModule2", progress);
ListModules(service);
service.Uninstall("TestModule1", progress);
ListModules(service);
}
示例2: GetBestMove
public static ChessMove GetBestMove(ChessBoard board, int depth, Progress progress)
{
Evaluator e = new Evaluator();
EvaluatedMove root = new EvaluatedMove(null, board);
e.Minimax(root, depth, progress);
EvaluatedMove[] bestMoves = root.Next.Where(m => (m != null) && (m.BestNextMoveValue == root.BestNextMoveValue)).ToArray();
IOrderedEnumerable<EvaluatedMove> orderedMoves = bestMoves.OrderBy(m => m.MateDepth); //.ThenBy(m => board[m.Move.Source]);
if (board.IsBlacksTurn)
orderedMoves = orderedMoves.ThenBy(m=>m.AccumulatedMoveValues);
else
orderedMoves = orderedMoves.ThenByDescending(m => m.AccumulatedMoveValues);
EvaluatedMove[] bestOrderedMoves = orderedMoves.ToArray();
if (random == null) random = new Random();
int moveIndex = -1;
for (int i = 1; i < bestOrderedMoves.Length; i++ )
{
if ((bestOrderedMoves[i].AccumulatedMoveValues != bestOrderedMoves[i - 1].AccumulatedMoveValues)
/*|| (board[bestOrderedMoves[i].Move.Source] != board[bestOrderedMoves[i - 1].Move.Source])*/
|| (bestOrderedMoves[i].MateDepth != bestOrderedMoves[i-1].MateDepth))
{
moveIndex = random.Next(i);
break;
}
}
if (moveIndex < 0)
moveIndex = random.Next(bestOrderedMoves.Length);
return bestOrderedMoves[moveIndex].Move;
}
示例3: btnCompare_Click
private async void btnCompare_Click(object sender, EventArgs e)
{
if (!Directory.Exists(txtFolder1.Text))
throw new ApplicationException("Directory does not exist");
if (!Directory.Exists(txtFolder2.Text))
throw new ApplicationException("Directory does not exist");
if (CurrentWorkspace != null)
{
traverse.ExcludeFolders.AddRange(CurrentWorkspace.Exclusions);
traverse.ExcludePatterns.AddRange(CurrentWorkspace.ExclusionPatterns);
}
var progressIndicator = new Progress<string>(ReportScanProgress);
await traverse.Compare(txtFolder1.Text, txtFolder2.Text, progressIndicator);
differences = traverse.Differences;
//view = new BindingListView<FileDiff>(differences);
//dataGridView1.DataSource = view;
lblStatus.Text = string.Format("Scanned {0} directories, {1} differences", traverse.TotalDirectories, traverse.Differences.Count());
DrawTree(DiffType.Lenght | DiffType.LastWritten | DiffType.ExistInSourceOnly | DiffType.ExistInDestinationOnly);
}
示例4: MeasureButton_Click
private async void MeasureButton_Click(object sender, RoutedEventArgs e)
{
string message = null;
try
{
var symbol = this.Resources["PolylineSymbol"] as LineSymbol;
var progress = new Progress<GeometryEditStatus>(OnStatusUpdated);
var geometry = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polyline, symbol, progress);
var layer = MyMapView.Map.Layers["ResultLayer"] as GraphicsLayer;
if (layer == null)
return;
layer.Graphics.Clear();
_measurements.Clear();
TotalLength.Text = TotalArea.Text = string.Empty;
}
catch (TaskCanceledException)
{
}
catch (Exception ex)
{
message = ex.Message;
}
if (!string.IsNullOrWhiteSpace(message))
await new MessageDialog(message).ShowAsync();
}
示例5: DbOperationThread
public DbOperationThread(etDbOperation eOpType, TestApplet formParent, string sPath)
{
m_eOperationType = eOpType;
m_formParent = formParent;
m_sPath = sPath;
m_Progress = m_formParent.UpdateProgressBar;
}
示例6: TakeSnapshot
public async Task TakeSnapshot(IProgress<Tuple<BackupStage, int>> Progress) {
Contract.Requires(Progress != null);
Progress.Report(Tuple.Create(BackupStage.AppData, 0));
var currentSettings = Settings.CurrentSettings;
var currentProfile = Profile.CurrentProfilePath();
var snapshotDir = GetSnapshotPath(currentSettings);
var appDataProgress = new Progress<int>(p => Progress.Report(Tuple.Create(BackupStage.AppData, p)));
try {
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
await isoStore.CopyDirectoryAsync(currentProfile, snapshotDir, appDataProgress);
await SaveMultimedia(isoStore, snapshotDir, Progress);
SaveCompletedTimeStamp(snapshotDir, isoStore);
}
}
catch (IsolatedStorageException) {
//Log
throw;
}
}
示例7: button1_Click
private async void button1_Click(object sender, EventArgs e)
{
cancelSource = new CancellationTokenSource();
IProgress<int> progress = new Progress<int>((processValue) => { this.progressBar1.Value = processValue; });
this.textBox1.AppendText("Starting work, please wait...");
this.button1.Enabled = false;
this.button2.Enabled = true;
WasteTimeObject ad = new WasteTimeObject();
ad.ShowProcess += UpdateProgress;
try
{
Task<string> task = Task.Run(() => ad.GetSlowString(1, 10, progress, cancelSource.Token));
DoingSomethings();
this.textBox1.AppendText("\r\nDoingSomethings is over....");
string result = await task;
this.textBox1.AppendText(result);
this.button2.Enabled = false;
}
catch (OperationCanceledException)
{
textBox1.AppendText("\r\nYou canceled the operation....");
}
}
示例8: bSearch_Click
private void bSearch_Click(object sender, EventArgs e)
{
var text = tSearch.Text.Trim();
if(text.Length > 0)
{
flpProduct.Controls.Clear();
Progress<ProductItem> itemProgress = new Progress<ProductItem>(
pi =>
{
flpProduct.Invoke(
(MethodInvoker)delegate
{
flpProduct.Controls.Add(pi);
});
});
//await Task.Factory.StartNew(() => LoadingThread.LoadProduct(@"Select * from inventory where title like '%" + text + "%'", itemProgress));
new Loading("Searching product",
() => LoadingThread.LoadProduct(@"Select * from inventory where title like '%" + text + "%'", itemProgress));
flpMessage.Visible = false;
flpProduct.Visible = true;
}
else
{
flpMessage.Visible = true;
flpProduct.Visible = false;
}
}
示例9: WorkWithImageFileByteArrayTestAsync
public async Task WorkWithImageFileByteArrayTestAsync()
{
var progressEncrypt = new Progress<StreamCryptorTaskAsyncProgress>();
var progressDecrypt = new Progress<StreamCryptorTaskAsyncProgress>();
progressEncrypt.ProgressChanged +=
(s, e) => { Console.WriteLine("Encrypting: " + e.ProgressPercentage + "%\n"); };
progressDecrypt.ProgressChanged +=
(s, e) => { Console.WriteLine("Decrypting: " + e.ProgressPercentage + "%\n"); };
var rawFile = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
var outputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
const string privateKey = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
const string publicKey = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
var keyPair = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));
Console.Write("Encrypting testfile . . .\n");
var encryptedFile =
await
Cryptor.EncryptFileWithStreamAsync(keyPair.PrivateKey, keyPair.PublicKey,
Utilities.HexToBinary(publicKey), rawFile, progressEncrypt, outputDirectory, ".test", true);
Console.Write("Decrypting testfile . . .\n");
var decryptedFileObject =
await
Cryptor.DecryptFileWithStreamAsync(keyPair.PrivateKey,
Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile),
progressDecrypt);
Console.Write("Get checksum of testfiles . . .\n");
Assert.AreEqual(Utils.GetChecksum(rawFile), Utils.GetChecksum(decryptedFileObject.FileData));
//clear garbage
File.Delete(Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile));
}
示例10: StartSpam
private async void StartSpam(object sender, RoutedEventArgs e)
{
var progress = new Progress<string>(s => TextBoxSpam.AppendText(s));
await Task.Factory.StartNew(() => LongWork(progress));
TextBoxSpam.AppendText(Environment.NewLine + "Complete");
}
示例11: Train
/// <summary>
/// Train the network using specialized strategies.
/// </summary>
/// <returns>Whether the training was successful.</returns>
public bool Train(IControler controler, Progress progress)
{
TrainingConfig config = controler.TrainingConfiguration;
int patternCount = controler.PatternCount;
int epochs = config.AutoTrainingEpochs.Value;
int success = (int)(patternCount * config.AutoTrainingPercentSuccessful.Value);
int howmany = controler.CountSuccessfulPatterns();
if(howmany >= success)
return true;
int timeout = epochs;
while(timeout-- >= 0)
{
if(progress != null)
progress((int)(100 * (epochs - (double)timeout) / epochs));
for(int i=0;i<patternCount;i++)
{
controler.SelectShuffledPattern(i);
controler.NeuralNetwork.TrainCurrentPattern(true, false);
}
howmany = controler.CountSuccessfulPatterns();
if(howmany >= success)
return true;
}
// CLEAN UP:
//controler.CalculateCurrentNetwork();
return false;
}
示例12: Download
public static async Task Download(this IBlobStorage blob, string key, Action<BlobProgress> progress, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(key)) return;
progress(new BlobProgress(null, BlobProgressState.Running, default(ProgressInBytes)));
try
{
var sizeInBytes = 0;
var progressReporter = new Progress<ProgressInBytes>(p => progress(new BlobProgress(null, BlobProgressState.Running, p)));
using (var stream = await blob.Get(key, progressReporter, cancellationToken).ConfigureAwait(false))
{
try
{
sizeInBytes = (int)stream.Length;
}
catch (NotSupportedException) { }
}
var uri = await blob.GetUri(key).ConfigureAwait(false);
progress(new BlobProgress(uri, BlobProgressState.Succeeded, new ProgressInBytes(sizeInBytes, sizeInBytes)));
}
catch
{
progress(new BlobProgress(null, BlobProgressState.Failed, default(ProgressInBytes)));
}
}
示例13: FetchAsync
public async Task<TempPackage> FetchAsync(Package pkg, Progress progress)
{
var user = pkg.Location.Host;
var project = pkg.Location.Segments.Skip(1).SingleOrDefault()?.Trim('/');
var props = pkg.Location.ParseQueryString();
var url = $"https://api.github.com/repos/{user}/{project}/releases/latest";
using (var httpClient = NetUtils.HttpClient())
{
var content = await httpClient.GetStringAsync(url);
var json = fastJSON.JSON.Parse(content) as IDictionary<string, object>;
var assets = json["assets"] as IList<object>;
var asset = NarrowAssets(assets, props);
var pkgUrlString = asset["browser_download_url"] as string;
Uri pkgUri;
if (!Uri.TryCreate(pkgUrlString, UriKind.Absolute, out pkgUri))
{
throw new UriFormatException($"Could not parse output from Github API, failed to parse URI: '{pkgUrlString}'");
}
var result = new TempPackage
{
Package = pkg,
WorkDirectory = new TempDirectory("winston"),
FileName = pkgUri.LastSegment()
};
using (var download = File.Open(result.FullPath, FileMode.Create, FileAccess.ReadWrite))
{
await httpClient.DownloadFileAsync(pkgUri, download, progress);
}
progress?.CompletedDownload();
return result;
}
}
示例14: AddFolder
/// <summary>
/// Add the folder into the media library.
/// </summary>
public void AddFolder(string path)
{
// make sure the folder isnt already in the list
bool exists = false;
this.Foreach (delegate (TreeModel model, TreePath tree_path, TreeIter iter)
{
Folder node = (Folder) model.GetValue (iter, 0);
if (node.Path == path) exists = true;
return exists;
});
// add the folder if it isnt already in the list
if (exists)
library.MainPage.ThrowError ("The folder is already in the library:\n" + path);
else
{
Folder folder = new Folder (path);
this.AppendValues (root_iter, folder);
library.MainPage.DataManager.AddFolder (folder);
// load the files within the directory
Progress progress = new Progress (library.MediaBox);
progress.Start (Utils.FileCount (path));
progress.Push ("Waiting in queue: " + Utils.GetFolderName (path));
// queue process
delegate_queue.Enqueue (delegate {
addDirRecurse (path, progress, folder);
progress.End ();
});
}
}
示例15: MainWindow
public MainWindow()
{
AppInfo.Instance.Value.IsClosing = false;
Crypto.LoadKey();
progress = new Progress(this);
InitializeComponent();
if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.username))
AppInfo.Instance.Value.Username = Crypto.Decrypt(Properties.Settings.Default.username);
if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.password))
AppInfo.Instance.Value.Password = Crypto.Decrypt(Properties.Settings.Default.password);
login = new Login();
if (string.IsNullOrWhiteSpace(AppInfo.Instance.Value.Username))
{
login.ShowDialog();
}
git = new Github(AppInfo.Instance.Value.Username, AppInfo.Instance.Value.Password);
Initialize();
}