Mohammad Noori
Mohammad Noori

Reputation: 147

My Application Crashed by this Error : Attempted to read or write protected memory

I have developed a winform application (using vs 2010 C#).in this application i used a com object and this object has some events.one of them is:

void a_Received(object sender, ReceivedEvent e)
{
    richTextBox1.Text = e.Message;
}

Another part of code that fire this event is like this:

 private void btnSendMessage_Click(object sender, EventArgs e)
{
    MyComObject obj = new MyComObject();
    obj.SendCommand(txtCommand.Text);
}

so some times based on command , 2 or more message recieved Simultaneously by event and i got this exception: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

and if only one message come (by event) every thing is good.

so what is the problem. what can i do?

EDIT: Exception will happen when all message that recieved processed (and processed successfully) at the end of code (I mean after } of event).

StackTrace :

at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageA(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at IranAir.Program.Main() in C:\Users\Administrator\Desktop\Gabriel\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

Upvotes: 0

Views: 85

Answers (1)

Seth Kitchen
Seth Kitchen

Reputation: 1566

You cannot have two threads writing to the same file simultaneously. That's why if you try to delete a file that's in use, Windows Pops-up saying "this file is in use." When one file is being used windows is protecting the file from being obstructed by another process. You need to make sure only one message is being written at a time. Set up a queue or check if the file is being used. See this post:

Is there a way to check if a file is in use?

Upvotes: 1

Related Questions