Cause Object to respond to a button click

I am looking for a way to get an object with a running process to respond to a Windows Forms button. Everything in this utility happens in only one "main" form of a Windows application.

The process is chewed through a bunch of files in the folder, and I want to put the "Pause" button on the form.

I could create a global variable, change its state with a button, and check the object's state of the variable as part of its process.

But I want to write better software, and I suspect there is a way with delegates or events or with some form of listener design template or ... to make it more elegant.

Thoughts?

+3
source share
2 answers

- . BackgroundWorker, Windows. ? , (, ), , .

, . , BackgroundWorker:

private BackgroundWorker _worker = new BackgroundWorker();

:

_worker.WorkerReportsProgress = true;

_worker.DoWork += DoWork;
_worker.ProgressChanged += ProgressChanged;
_worker.RunWorkerCompleted += RunWorkerCompleted;

, :

private void DoWork(object sender, DoWorkEventArgs e)
{
    // do the work here
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // e.UserState is a value that you can pass anything to
    // like a string for a status label

    // e.ProgressPercentage is an integer that you specify letting
    // this event know what step the process is at - this is well
    // used for a progress bar
}

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // e.Result is a value that you can pass anything to
    // like a reference to an object with the finished product
    // or whatever makes sense in your case
}

, , :

_worker.RunWorkerAsync();

, DoWork :

// NOTE: make sure to pass AT LEAST a value of 1 for the percentage
// or the event handler will NEVER fire. Further, someValue can be anything
// an instance of an object with data or just a string, or nothing for that
// matter - it up to you
_worker.ReportProgress(1, someValue);
+1

, - / BackgroundWorker? - , -. event wait handle ( "" , ).

:

KeepWorking = new EventWaitHandle(true, EventResetMode.ManualReset);

:

while (KeepWorking.WaitOne())
{
    ...
}

:

KeepWorking.Reset(); // To pause it
KeepWorking.Set(); // To unpause it
0

All Articles