嗯,我有一个功能,需要从电脑的屏幕截图,但不幸的是,它阻止主用户界面,所以我决定做一个异步[Threaded调用]它;但是,我觉得麻烦等待在返回位图之前Thread的结果。异步等待一个线程完成
这里是我的代码:
/// <summary>
/// Asynchronously uses the snapshot method to get a shot from the screen.
/// </summary>
/// <returns> A snapshot from the screen.</returns>
private Bitmap SnapshotAsync()
{
Bitmap image = null;
new Thread(() => image = Snapshot()).Start();
while (image == null)
{
new Thread(() => Thread.Sleep(500)).Start(); //Here i create new thread to wait but i don't think this is a good way at all.
}
return image;
}
/// <summary>
/// Takes a screen shots from the computer.
/// </summary>
/// <returns> A snapshot from the screen.</returns>
private Bitmap Snapshot()
{
var sx = Screen.PrimaryScreen.Bounds.Width;
var sy = Screen.PrimaryScreen.Bounds.Height;
var shot = new Bitmap(sx, sy, PixelFormat.Format32bppArgb);
var gfx = Graphics.FromImage(shot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(sx, sy));
return shot;
}
虽然上面的方法工作在异步模式,因为我想要的,我相信它可以得到改善。特别是我执行数百个线程来等待结果的方式,我确信的方式并不好。
所以我真的需要任何人看看代码并告诉我如何改进它。
[注意我使用.NET 3.5]
并提前致谢。这里
问题夏娃和料仓的帮助下解决是最好的2回答
- 1:
> private void TakeScreenshot_Click(object sender, EventArgs e)
> {
> TakeScreenshotAsync(OnScreenshotTaken);
> }
>
> private static void OnScreenshotTaken(Bitmap screenshot)
> {
> using (screenshot)
> screenshot.Save("screenshot.png", ImageFormat.Png);
> }
>
> private static void TakeScreenshotAsync(Action<Bitmap> callback)
> {
> var screenRect = Screen.PrimaryScreen.Bounds;
> TakeScreenshotAsync(screenRect, callback);
> }
>
> private static void TakeScreenshotAsync(Rectangle bounds, Action<Bitmap> callback)
> {
> var screenshot = new Bitmap(bounds.Width, bounds.Height,
> PixelFormat.Format32bppArgb);
>
> ThreadPool.QueueUserWorkItem((state) =>
> {
> using (var g = Graphics.FromImage(screenshot))
> g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size);
>
> if (callback != null)
> callback(screenshot);
> });
> }
- 2:
> void SnapshotAsync(Action<Bitmap> callback)
> {
> new Thread(Snapshot) {IsBackground = true}.Start(callback);
> }
> void Snapshot(object callback)
> {
> var action = callback as Action<Bitmap>;
> var sx = Screen.PrimaryScreen.Bounds.Width;
> var sy = Screen.PrimaryScreen.Bounds.Height;
> var shot = new Bitmap(sx, sy, PixelFormat.Format32bppArgb);
> var gfx = Graphics.FromImage(shot);
> gfx.CopyFromScreen(0, 0, 0, 0, new Size(sx, sy));
> action(shot);
> }
用途,例如,通过一个按钮的点击:
void button1_Click(object sender, EventArgs e) { SnapshotAsync(bitmap => MessageBox.Show("Copy successful!")); }
您在使用.NET 4.5? – Mir
不,先生,我不能使用它,我只是想在.Net 3.5上的解决方案 –