如果锁定不起作用,如何修复“对象在其他地方当前正在使用”的异常

时间:2019-07-16 17:09:17

标签: c#

我正在尝试创建视频聊天,所以我发送和接收图像,但是遇到下面将要描述的异常。我使用了github.com/mesta1中的一些技术来实现与摄像头的连接并获取视频,然后我尝试使用套接字发送它。这是代码,凡事都发生了。SaveJpeg函数中的异常发生在标记行中。我已经尝试过锁,监视器和类似的东西,但是它们不起作用。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using AForge.Video;
using AForge.Video.DirectShow;
namespace AForge.WindowsForms
{
public partial class Form1 : Form
{
    static object o=new object();
    Socket socket;
    byte[] buffer;
    private bool isTrue = true;
    //const string ip = "172.20.10.2";
    const string ip = "127.0.0.1";
    const int port = 9390;
    //const int port = 9786;
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
    private FilterInfoCollection videoDevicesList;
    private IVideoSource videoSource;

    public Form1()
    {
        InitializeComponent();
        // get list of video devices
        videoDevicesList = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        foreach (FilterInfo videoDevice in videoDevicesList)
        {
            cmbVideoSource.Items.Add(videoDevice.Name);
        }
        if (cmbVideoSource.Items.Count > 0)
        {
            cmbVideoSource.SelectedIndex = 0;
        }
        else
        {
            MessageBox.Show("No video sources found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        // stop the camera on window close
        this.Closing += Form1_Closing;
    }

    private void Form1_Closing(object sender, CancelEventArgs e)
    {
        // signal to stop
        ClosingConnections();
        if (videoSource != null && videoSource.IsRunning)
        {
            videoSource.SignalToStop();
        }
    }

    private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        //          Thread.Sleep(1000);
        Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
        pictureBox1.Image = bitmap;
        //Thread t = new Thread(VideoSender);
        //t.Start();
        VideoSender();
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        GettingConnection();
        videoSource = new VideoCaptureDevice(videoDevicesList[cmbVideoSource.SelectedIndex].MonikerString);
        videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
        videoSource.Start();
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        videoSource.SignalToStop();
        this.isTrue = false;
        ClosingConnections();
        if (videoSource != null && videoSource.IsRunning && pictureBox1.Image != null)
        {
            pictureBox1.Image.Dispose();
        }
    }


    private void VideoSender()
    {       
        if (pictureBox1.Image != null)
        {
            MemoryStream stream = new MemoryStream(buffer);
            //pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            SaveJpeg(stream,pictureBox1.Image,80);
            //var size = stream.ToArray().Length;
            socket.Send(buffer);
            stream.Position = 0;
        }
    }
    private void GettingConnection()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        buffer = new byte[100000];
        socket.Connect(endPoint);

    }
    public void ClosingConnections()
    {
        socket.Shutdown(SocketShutdown.Both);
        socket.Close();
    }
    public static void SaveJpeg(MemoryStream stream, Image img, int quality)
    {
        if (quality < 0 || quality > 100)
            throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");

        // Encoder parameter for image quality 
        EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
        // JPEG image codec 
        ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;                      
        img.Save(stream, jpegCodec, encoderParams);  //error line
    }
    private static ImageCodecInfo GetEncoderInfo(string mimeType)
    {
        // Get image codecs for all image formats 
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

        // Find the correct image codec 
        for (int i = 0; i < codecs.Length; i++)
            if (codecs[i].MimeType == mimeType)
                return codecs[i];

        return null;
    }
}

} 我也可以提供堆栈跟踪。

at System.Drawing.Image.get_RawFormat()
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle rect)
at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

我希望我的程序能够正常运行,但是我遇到了异常

0 个答案:

没有答案