In some long-running optimization jobs, it may be desired to interrupt the job based on conditions that may or may not depend on the state of the optimization job itself. While Gurobi provides callbacks to implement this, C# users are familiar with using the CancellationToken type. In this article, we will show how these can work together.
Below is an example of a callback that monitors a CancellationToken
:
class CancellationCallback : GRBCallback
{
private readonly CancellationToken _token;
public CancellationCallback(CancellationToken token)
{
_token = token;
}
protected override void Callback()
{
if(_token.IsCancellationRequested)
{
Abort();
}
}
}
The class can be used as follows. Here we simply start a timer on a separate thread to cancel an optimization job after two seconds. CancellationTokenSource is used to control the CancellationToken
passed to the callback.
var cts = new CancellationTokenSource();
model.SetCallback(new CancellationCallback(cts.Token));
new Thread(() => { Thread.Sleep(2000); cts.Cancel(); }).Start();
model.Optimize();
Notes:
- Note that the thread must be started before the call to
model.Optimize()
, since the latter call is blocking. - Keep in mind that Gurobi may use as many threads as you have cores available unless you set the Threads parameter. Your process that would manage the cancellation will require compute resources, so make sure you limit the number of threads for Gurobi.
Comments
0 comments
Article is closed for comments.