public class ValuesController : ApiController
{
// logger
private static Logger logger =
NLog.LogManager.GetCurrentClassLogger();
// POST api/values
[HttpPost]
public HttpResponseMessage Post()
{
try
{
//Use
QueueBackgroundWorkItem to run the async long-running task
Func<CancellationToken, Task>
workItem = longRunningWriteLogAsync;
HostingEnvironment.QueueBackgroundWorkItem(workItem);
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception ex)
{
logger.Fatal(ex.Message);
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
private void
logRunningWriteLog(CancellationToken cancellationToken)
{
bool
isCancellationHadBeenTriggered = false;
for (int i = 0; i
< 50; i++)
{
//Detect the
CancellationToken
if
(!isCancellationHadBeenTriggered &&
cancellationToken.IsCancellationRequested)
{
logger.Info("Signaled
cancellation!");
isCancellationHadBeenTriggered = true;
//break; //stop the loop right away
//or do the
cancellation callback
}
logger.Info(String.Format("QBW
Test-{0}", i));
Thread.Sleep(2000);
}
}
private async Task
longRunningWriteLogAsync(
CancellationToken
cancellationToken)
{
this.logRunningWriteLog(cancellationToken);
}
}
|
沒有留言:
張貼留言