我制作了一个小小的winform应用程序,每隔10分钟,应用程序会截取桌面的屏幕截图并使用base64解码格式的webservice发送。
我使用了一个定时器控件,每10分钟触发一次,并使用后台工作程序更新UI上最后发送的截屏时间。
问题是应用程序在一段时间后开始挂起,我做了一些谷歌搜索,发现任务并行库是长期运行过程的正确方法。但我对TPL了解不多。
请指导我如何在我的应用中实施TPL 请说出正确而有效的方法。
代码是
void timer1_Tick(object sender, EventArgs e)
{
timer1.Interval = 600000 ; //10mins
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate { screenShotFunction(); }));
}
else
{
screenShotFunction();
}
}
private void screenShotFunction()
{
printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
mainSendFunction();
}
private void mainSendFunction()
{
try
{
//code for webservice and base64 decoding
}
catch (Exception)
{
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
答案 0 :(得分:0)
我不是TPL的专家,但应该这样做:
首先创建一个处理任务的方法。
private async void ScreenShotTask()
{
try
{
while (true)
{
_cancelToken.ThrowIfCancellationRequested();
screenShotFunction();
await Task.Delay(new TimeSpan(0, 0, 10, 0), _cancelToken);
}
}
catch (TaskCanceledException)
{
// what should happen when the task is canceled
}
}
我使用await Task.Delay
代替Thread.Sleep
,因为它可以取消。
这就是你实际开始这项任务的方式:
private CancellationTokenSource _cancelSource;
private CancellationToken _cancelToken; // ScreenShotTask must have access to this
private void mainMethod()
{
_cancelSource= new CancellationTokenSource();
_cancelToken = cancelSource.Token;
Task.Factory.StartNew(ScreenShotTask, _cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
这是你取消任务的方法:
_cancelSource.Cancel();