Hooch
Hooch

Reputation: 29673

Locking WebClient - multithreaded application

I have webClient that I am using in my bot:

using System;
using System.Net;

namespace Game_Bot
{
    class WebClientEx : WebClient
    {
        public CookieContainer CookieContainer { get; private set; }

        public WebClientEx()
        {
            CookieContainer = new CookieContainer();
        }

        public void ClearCookies()
        {
            CookieContainer = new CookieContainer();
        }

        protected override WebRequest GetWebRequest(Uri address)
        {

            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = CookieContainer;
            }
            return request;
        }
    }

}

I have one object of my webclient. There are many methods that use it. If two threads want to use that webClient to download I got error saying that webClent can run only one operation at the time. How can I modify that class so that when one thread is using it the other one have to wait. I need to lock it in some way.

Upvotes: 1

Views: 1228

Answers (2)

Marco
Marco

Reputation: 57573

You could use a Mutex for example.
When first client makes a request, you get the property of the mutex, releasing it when the call completes.
When other clients make request, first you wait for mutex and the job is done.

Upvotes: 0

BrandonZeider
BrandonZeider

Reputation: 8152

You can use the lock statement.

Upvotes: 2

Related Questions