本文整理汇总了C#中System.ComponentModel.BackgroundWorker.CancelAsync方法的典型用法代码示例。如果您正苦于以下问题:C# BackgroundWorker.CancelAsync方法的具体用法?C# BackgroundWorker.CancelAsync怎么用?C# BackgroundWorker.CancelAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.ComponentModel.BackgroundWorker
的用法示例。
在下文中一共展示了BackgroundWorker.CancelAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CancelAsyncNonBusy
public void CancelAsyncNonBusy ()
{
BackgroundWorker b = new BackgroundWorker ();
b.WorkerSupportsCancellation = true;
Assert.IsFalse (b.IsBusy, "#1");
b.CancelAsync ();
}
示例2: MultiProgressDialog
MultiProgressDialog(string status, List<string> names, Action<ProgressDelegate, CancelDelegate> work, Action finished = null)
{
InitializeComponent();
Status = status;
progress = names.Select(name => 0).ToList();
SetupGrid(names);
worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
worker.DoWork += (s, e) =>
{
work((child, done, total) => SetProgress(child, done, total), forceCancel =>
{
if (forceCancel)
worker.CancelAsync();
if (worker.CancellationPending)
e.Cancel = true;
return e.Cancel;
});
};
worker.ProgressChanged += (s, e) =>
{
for (var ctr = 0; ctr < progressBars.Count; ++ctr)
progressBars[ctr].Progress = progress[ctr];
};
worker.RunWorkerCompleted += (s, e) =>
{
canClose = true;
Close();
if (e.Error != null)
throw new Exception($"Background task failed: {e.Error.Message}", e.Error);
if ((!e.Cancelled) && (finished != null))
finished();
};
worker.RunWorkerAsync();
}
示例3: Window4
public Window4()
{
InitializeComponent();
this.PlotModel = new PlotModel();
this.PlotModel.Series.Add(new FunctionSeries());
DataContext = this;
var worker = new BackgroundWorker { WorkerSupportsCancellation = true };
double x = 0;
worker.DoWork += (s, e) =>
{
while (!worker.CancellationPending)
{
lock (this.PlotModel.SyncRoot)
{
this.PlotModel.Title = "Plot updated: " + DateTime.Now;
this.PlotModel.Series[0] = new FunctionSeries(Math.Sin, x, x + 4, 0.01);
}
x += 0.1;
PlotModel.InvalidatePlot(true);
Thread.Sleep(100);
}
};
worker.RunWorkerAsync();
this.Closed += (s, e) => worker.CancelAsync();
}
示例4: ExtractSin
public static void ExtractSin(BackgroundWorker sender, string sinfile, string outfile, bool log = true)
{
using (FileStream stream = new FileStream(sinfile, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(stream))
{
if (log)
Logger.WriteLog("Verifying extracted Sin File"); ;
if (!SinFile.VerifySin(br))
{
sender.CancelAsync();
return;
}
List<SinFile.BlockInfoHeader> bihs = null;
int SinVer = SinFile.GetSinVersion(br);
switch (SinVer)
{
case 2:
bihs = SinFileV2.GetBIHs(br);
break;
case 3:
bihs = SinFileV3.GetBIHs(br);
break;
}
if (log)
Logger.WriteLog("Extracting image from Sin File " + Path.GetFileName(sinfile));
SinExtract.ExtractSinData(sender, br, bihs, outfile, log);
}
}
示例5: Execute
public override bool Execute()
{
Log.LogMessage(string.Format("Starting to build '{0}'", ApplicationToBuild));
try
{
var aionBuilder = new AionBuilder(AionBuildProcess, null, Log);
var worker = new BackgroundWorker();
worker.DoWork += WorkerDoWork;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
aionBuilder.Build(ApplicationToBuild, ShouldRestoreCodeFromApp, BuildTimeOutInSeconds);
worker.CancelAsync();
Log.LogMessage(string.Format("Finished building '{0}'{1}", ApplicationToBuild, Environment.NewLine));
return aionBuilder.IsBuildSuccesful;
}
catch (Exception e)
{
Log.LogError(e.Message + " > " + e.StackTrace);
return false;
}
}
示例6: Process
private void Process()
{
var pbViewModel = new ProgressBarViewModel();
var pbView = new ProgressBarView { DataContext = pbViewModel };
pbView.Show();
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += (sender, args) =>
{
pbViewModel.Value = args.ProgressPercentage;
};
worker.RunWorkerCompleted += (sender, args) =>
{
if (args.Cancelled)
{
MessageBox.Show("Расчет прерван");
}
pbView.Close();
};
pbViewModel.Cancelled += (sender, args) =>
{
worker.CancelAsync();
};
worker.RunWorkerAsync();
}
示例7: OnStart
/// <summary>
/// Executed when the service starts
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
serviceLog.WriteEntry("IntelliMailService started");
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(StartIdleProcess);
if (worker.IsBusy)
worker.CancelAsync();
worker.RunWorkerAsync();
}
示例8: Main
static void Main(string[] args)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.WorkerSupportsCancellation = true;
bw.RunWorkerAsync();
Console.WriteLine("Window closer started\nPress any key to exit...");
Console.ReadKey();
bw.CancelAsync();
bw.DoWork -= bw_DoWork;
}
示例9: DocumentUploader
public DocumentUploader()
{
InitializeComponent();
CmsWebService service = new CmsWebService();
WindowsIdentity windowsUser = WindowsIdentity.GetCurrent();
if (windowsUser == null)
{
return;
}
List<string> temp = windowsUser.Name.Split('\\').ToList();
User user = service.GetUser(temp.Last());
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["CmsEntities"];
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(settings.ConnectionString);
SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(builder.ProviderConnectionString);
lblTitle.Text = string.Format("Document Version Imports: by {0} into {1} on {2}", user.UserName, conn.InitialCatalog, conn.DataSource);
mMetaData.UserId = user.Id;
using (mWorker = new BackgroundWorker())
{
mWorker.WorkerSupportsCancellation = true;
mWorker.WorkerReportsProgress = true;
mWorker.ProgressChanged += bw_ProgressChanged;
mWorker.RunWorkerCompleted += bw_RunWorkerCompleted;
mWorker.DoWork += (s1, e1) =>
{
try
{
if (mWorker.CancellationPending)
{
mWorker.CancelAsync();
mWorker.Dispose();
}
else
{
//WORK
ImportDocuments(mWorker);
}
}
catch (ThreadAbortException)
{
Thread.ResetAbort();
}
};
}
}
示例10: Generate
public void Generate(int size, RenderContext context)
{
m_Context = context;
m_Worker = new BackgroundWorker();
m_Worker.WorkerReportsProgress = true;
m_Worker.WorkerSupportsCancellation = true;
m_Worker.DoWork += bgw_DoWork; //Work Event
m_Worker.RunWorkerCompleted += m_Worker_RunWorkerCompleted;
//Event that is run in the background;
Console.WriteLine("Opening new Thread");
m_Worker.RunWorkerAsync(size);
m_Worker.CancelAsync();
m_Worker.Dispose();
}
示例11: Main
static void Main(string[] args)
{
var bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += Worker_DoWork;
bw.ProgressChanged += Worker_ProgressChanged;
bw.RunWorkerCompleted += Worker_Completed;
bw.RunWorkerAsync();
Console.WriteLine("Press C to cancel work");
do
{
if (Console.ReadKey(true).KeyChar == 'C')
{
bw.CancelAsync();
}
}
while(bw.IsBusy);
}
示例12: ShowSpareDetailsInBackground
private void ShowSpareDetailsInBackground(IList selectedItems)
{
ParentWindow.edtStatus.Content = "загрузка";
BackgroundShowDetails = new BackgroundWorker();
BackgroundShowDetails.DoWork += new DoWorkEventHandler(BackgroundShowDetails_DoWork);
BackgroundShowDetails.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundShowDetails_RunWorkerCompleted);
if (BackgroundShowDetails.IsBusy)
BackgroundShowDetails.CancelAsync();
BackgroundShowDetails.RunWorkerAsync(selectedItems);
}
示例13: StartContentBuilding
private void StartContentBuilding()
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
#region Events
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
EditorStatus = EditorStatus.LOADING;
Database.Instance.LoadData();
progressStatusBarItem.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
progressStatusBarItem.Content = "Building content...";
}
));
#region Resource Builder Events
ResourceBuilder.Instance.OnPercentChanged += new EventHandler<OnPercentChangedEventArgs>(delegate(object o, OnPercentChangedEventArgs OnPercentChangedEventArgs)
{
worker.ReportProgress(OnPercentChangedEventArgs.Percent);
});
ResourceBuilder.Instance.OnBuildFailed += new EventHandler<EventArgs>(delegate(object onBuildFailed, EventArgs onBuildFailedArgs)
{
worker.CancelAsync();
});
#endregion
ResourceBuilder.Instance.BuildContent();
};
worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
int percentage = args.ProgressPercentage;
progressBar.Value = percentage;
};
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
EditorStatus = EditorStatus.IDLE;
progressStatusBarItem.Content = "Ready";
progressBar.Value = 0;
Output.AddToOutput("Building of content files completed...");
sceneGraph.Lighting.LoadContent();
gizmo = new GizmoModules.GizmoComponent(GameApplication.Instance.GetGraphics(), spriteBatch);
gizmo.SetSelectionPool(WorldManager.Instance.GetActors().Values);
gizmo.ActiveSpace = GizmoModules.TransformSpace.Local;
gizmo.TranslateEvent += new GizmoModules.TransformationEventHandler(gizmo_TranslateEvent);
gizmo.RotateEvent += new TransformationEventHandler(GizmoRotateEvent);
gizmo.ScaleEvent += new TransformationEventHandler(GizmoScaleEvent);
// Set up the frame update timer
timer = new Timer();
xnaControl.ResetMouseState();
};
#endregion
worker.RunWorkerAsync();
}
示例14: getCPUCores
public static int getCPUCores()
{
BackgroundWorker bw1 = new BackgroundWorker();
bw1.WorkerSupportsCancellation = true;
threadsCounter = 0;
bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
bw1.RunWorkerAsync();
System.Threading.Thread.Sleep(200);
int singleThreadCount = threadsCounter;
bw1.CancelAsync();
threadsCounter = 0;
BackgroundWorker[] bwm = new BackgroundWorker[8];
for (int i = 0; i < 8; i++)
{
bwm[i] = new BackgroundWorker();
bwm[i].WorkerSupportsCancellation = true;
bwm[i].DoWork += new DoWorkEventHandler(bw_DoWork);
bwm[i].RunWorkerAsync();
}
System.Threading.Thread.Sleep(200);
int eightThreadsCount = threadsCounter;
for (int i = 0; i < 8; i++)
{
bwm[i].CancelAsync();
}
float performanceRatio = (float)eightThreadsCount / singleThreadCount;
int cpuCores = 1;
if (performanceRatio > 7)
{
cpuCores = 8;
}
else
if (performanceRatio > 3.5)
{
cpuCores = 4;
}
else
if (performanceRatio > 1.7)
{
cpuCores = 2;
}
return cpuCores;
}
示例15: ImportMasters
//.........这里部分代码省略.........
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
nameFile = textInfo.ToTitleCase(nameFile.ToLower());
//add name of master tape if not included
if (!inputBox.Items.Contains(nameFile))
{
inputBox.Items.Add(nameFile);
}
inputBox.Text = nameFile;
}
}
}
catch { Debug.WriteLine("Error in master gather"); }
//check if there is a media defined in the name using all combobox items
try
{
//check to make sure there is something selected
if (!ofd.FileName.Equals(string.Empty))
{
//get name of file without extension
foreach (string obj in mediaCombo.Items)
{
Debug.WriteLine("In media for loop");
if (!obj.ToLower().Equals("other"))
{
Debug.WriteLine("Does not equal other");
//string[] mediaItems = mediaCombo.DataSource.t
string nameFile = Path.GetFileNameWithoutExtension(ofd.FileName);
//get index of the word master
int index = nameFile.ToLower().IndexOf(obj.ToLower());
//add name of master tape if not included
if (index != -1)
{
Debug.WriteLine("Does not equal -1");
mediaCombo.Text = obj;
break;
}
}
}
}
}
catch { Debug.WriteLine("Error in media gather"); }
#endregion
//Set up buttons to add
Button confirmation = new Button() { Text = "OK", Left = 240, Width = 100, Top = 120 };
Button cancelButton = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 120 };
//button actions
cancelButton.Click += (senderPrompt, ePrompt) => { addMasters = false; masterPrompt.Close(); };
confirmation.Click += (senderPrompt, ePrompt) => { addMasters = true; masterTapeName = inputBox.Text; cameraMasterName = mediaCombo.Text; masterPrompt.Close(); };
//Add items to form
masterPrompt.Controls.Add(textLabel);
masterPrompt.Controls.Add(inputBox);
masterPrompt.Controls.Add(mediaCombo);
masterPrompt.Controls.Add(confirmation);
masterPrompt.Controls.Add(cancelButton);
masterPrompt.ShowDialog();
//Add entries or Cancel depending on button clicked
if (addMasters)
{
//gets extension of the file and acts accordingly
switch (GetExtensionOfFile(ofd))
{
case "csv":
UpdateStatusBarBottom("Importing " + masterTapeName + " Entries");
DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName));
break;
case "txt":
ofd.FileName = @"" + TempConvertToCSV(ofd);
UpdateStatusBarBottom("Importing " + masterTapeName + " Entries");
DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName), true);
break;
case "doc":
case "docx":
ofd.FileName = @"" + ConvertWordToCSVFile(ofd);
UpdateStatusBarBottom("Importing " + masterTapeName + " Entries");
DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName), true);
break;
default:
Debug.WriteLine("File was not a txt, doc, docx, or csv");
break;
}
}
else
{
worker.CancelAsync();
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
}
}