嗯,我有一個功能,需要從電腦的屏幕截圖,但不幸的是,它阻止主用戶界面,所以我決定做一個異步[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上的解決方案 –