Search Results

Search found 30085 results on 1204 pages for 'read only'.

Page 4/1204 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Mark Messages As Read in the Outlook 2010 Reading Pane

    - by Matthew Guay
    Do you ever feel annoyed that Outlook 2010 doesn’t mark messages as Read as soon as you click and view them in the Reading Pane?  Here we show you how to make Outlook mark them as read as soon as they’re opened. Mark as Read By default, Outlook will not mark a message as read until you select another message.  This can be annoying, because if you read a message and immediately click Delete, it will show up as an unread message in our Deleted Items folder. Let’s change this to make Outlook mark messages as read as soon as we view them in the Reading Pane.  Open Outlook and click File to open Backstage View, and select Options. In Options select Mail on the left menu, and under Outlook panes click on the Reading Pane button. Check the box Mark items as read when viewed in the Reading Pane to make Outlook mark your messages as read when you view them in the Reading Pane.  By default, Outlook will only mark a message read after you’ve been reading it for 5 seconds, though you can change this.  We set it to 0 seconds so our messages would be marked as read as soon as we select them. Click OK in both dialogs, and now your messages will be marked as read as soon as you select them in the reading pane, or soon after, depending on your settings. Conclusion Outlook 2010 is a great email client, but like most programs it has its quirks.  This quick tip can help you get rid of one of Outlook’s annoying features, and make it work like you want it to. And, if you’re still using Outlook 2007, check out our article on how to Mark Messages as Read When Viewed in Outlook 2007. Similar Articles Productive Geek Tips Make Outlook 2007 Mark Items as Read When Viewed in Reading PaneMake Mail.app’s Reading Pane More Like OutlookIntegrate Twitter With Microsoft OutlookSort Your Emails by Conversation in Outlook 2010Find Emails With Attachments with Outlook 2007’s Instant Search TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips All My Movies 5.9 CloudBerry Online Backup 1.5 for Windows Home Server Snagit 10 VMware Workstation 7 OpenDNS Guide Google TV The iPod Revolution Ultimate Boot CD can help when disaster strikes Windows Firewall with Advanced Security – How To Guides Sculptris 1.0, 3D Drawing app

    Read the article

  • Making ehcache read-write for test code and read-only for production code

    - by Rick
    I would like to annotate many of my Hibernate entities that contain reference data and/or configuration data with @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) However, my JUnit tests are setting up and tearing down some of this reference/configuration data using the Hibernate entities. Is there a recommended way of having entities be read-write during test setup and teardown but read-only for production code? Two of my immediate thoughts for non-ideal workarounds are: Using NONSTRICT_READ_WRITE, but I am not sure what the hidden downsides are. Creating subclassed entities in my test code to override the read-only cache annotation. Any recommendations on the cleanest way to handle this? (Note: Project uses maven.)

    Read the article

  • PHP zip->open returns error code 5 (Read Error)

    - by Manuel Kaspar
    We had a site running, that uses the php zip functionality. Everyhthing worked fine for month - now we moved to a new server and the script doesn't work! $zip-open() returns error Code 5 what is a read error. I found out, that it has to do with the size of the zip files, as they are about 60mb. Smaller sizes about 30mb are working. What could be the reason for that? I didn't find any configuration possiblility about the size of zip files! Thanks, Manu

    Read the article

  • Python faster way to read fixed length fields form a file into dictionary

    - by Martlark
    I have a file of names and addresses as follows (example line) OSCAR ,CANNONS ,8 ,STIEGLITZ CIRCUIT And I want to read it into a dictionary of name and value. Here self.field_list is a list of the name, length and start point of the fixed fields in the file. What ways are there to speed up this method? (python 2.6) def line_to_dictionary(self, file_line,rec_num): file_line = file_line.lower() # Make it all lowercase return_rec = {} # Return record as a dictionary for (field_start, field_length, field_name) in self.field_list: field_data = file_line[field_start:field_start+field_length] if (self.strip_fields == True): # Strip off white spaces first field_data = field_data.strip() if (field_data != ''): # Only add non-empty fields to dictionary return_rec[field_name] = field_data # Set hidden fields # return_rec['_rec_num_'] = rec_num return_rec['_dataset_name_'] = self.name return return_rec

    Read the article

  • Force blocking read after EAGAIN?

    - by Daniel Trebbien
    I have a file descriptor that is open for reading which may be non-blocking. What I need to do is simply read all data until reaching EOF and write that data to a writable file descriptor. As the process that performs this copying is not "aware" of anything that is going on around it, I don't think that I can do something useful while waiting for data, and I don't want to use a while loop (while errno is not EAGAIN) because I think that it would be wasteful. Is there a way to block or otherwise suspend execution of the copying process until data becomes available?

    Read the article

  • TCL How to read , extract and count the occurent in .txt file (Current Directory)

    - by Passion
    Hi Folks, I am beginner to scripting and vigorously learning TCL for the development of embedded system. I have to Search for the files with only .txt format in the current directory, count the number of cases of each different "Interface # nnnn" string in .txt file, where nnnn is a four or 32 digits max hexadecimal no and o/p of a table of Interface number against occurrence. I am facing implementation issues while writing a script i.e, Unable to implement the data structure like Linked List, Two Dimensional array. I am rewriting a script using multi dimension array (Pass values into the arrays in and out of procedure) in TCL to scan through the every .txt file and search for the the string/regular expression ‘Interface # ’ to count and display the number of occurrences. If someone could help me to complete this part will be much appreciated. Search for only .txt extension files and obtain the size of the file Here is my piece of code for searching a .txt file in present directory set files [glob *.txt] if { [llength $files] > 0 } { puts "Files:" foreach f [lsort $files] { puts " [file size $f] - $f" } } else { puts "(no files)" } I reckon these are all the possible logical steps behind to complete it i) Once searched and find the .txt file then open all .txt files in read only mode ii) Create a array or list using the procedure (proc) Interface number to NULL and Interface count to zero 0 iii) Scan thro the .txt file and search for the string or regular expression "interface # iv) When a match found in .txt file, check the Interface Number and increment the count for the corresponding entry. Else add new element to the Interface Number list v) If there are no files return to the first directory My o/p is like follows Interface Frequency 123f 3 1232 4

    Read the article

  • Python: slow read & write for millions of small files

    - by Jami
    I am building directory tree which has tons of subdirectories and files. The total directory count is somewhere along 256^32 subdirectories with 256 files in each end which are only a few bytes long. I did this so I would have fast access to these files (since i'm not searching and i'm just directly accessing then via a known file path) I have a python script that builds this filesystem and reads & writes those files. The problem is that when I reach more than 1Gb of total filesize, the read and write methods become extremely slow. Here's the function I have that reads the contents of a file (the file contains an integer string), adds a certain number to it, then writes it back to the original file. def addInFile(path, scoreToAdd): num = scoreToAdd try: shutil.copyfile(path, '/tmp/tmp.txt') fp = open('/tmp/tmp.txt', 'r') num += int(fp.readlines()[0]) fp.close() except: pass fp = open('/tmp/tmp.txt', 'w') fp.write(str(num)) fp.close() shutil.copyfile('/tmp/tmp.txt', path) I previously tried performing linux console commands but it was slower. I copy the file to a temporary file first then access/modify it then copy it back because i found this was faster than directly accessing the file. I think the cause of the slowdown is because there're tons of files. performing this function 1000 times sometimes reach 1 minute now, but before (when there were only a few files, 1000 calls was performed for only less than 1 second) How do you suggest I fix this?

    Read the article

  • Read/Write Files from the Content Provider

    - by drum
    I want to be able to create a file from the Content Provider, however I get the following error: java.io.Filenotfoundexception: /0: open file failed: erofs (read-only file system) What I am trying to do is create a file whenever an application calls the insert method from my Provider. This is the excerpt of the code that does the file creation: FileWriter fstream = new FileWriter(valueKey); BufferedWriter out = new BufferedWriter(fstream); out.write(valueContent); out.close(); Originally I wanted to use openFileOutput() but the function appears to be undefined. Anyone has a workaround to this problem? EDIT: I found out that I had to specify the directory as well. Here is a more complete snippet of the code: File file = new File("/data/data/Project.Package.Structure/files/"+valueKey); file.createNewFile(); FileWriter fstream = new FileWriter(file); BufferedWriter out = new BufferedWriter(fstream); out.write(valueContent); out.close(); I also enabled the permission <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> This time I got an error saying: java.io.IOException: open failed: ENOENT (No such file or directory)

    Read the article

  • implementing a read/write field for an interface that only defines read

    - by PaulH
    I have a C# 2.0 application where a base interface allows read-only access to a value in a concrete class. But, within the concrete class, I'd like to have read/write access to that value. So, I have an implementation like this: public abstract class Base { public abstract DateTime StartTime { get; } } public class Foo : Base { DateTime start_time_; public override DateTime StartTime { get { return start_time_; } internal set { start_time_ = value; } } } But, this gives me the error: Foo.cs(200,22): error CS0546: 'Foo.StartTime.set': cannot override because 'Base.StartTime' does not have an overridable set accessor I don't want the base class to have write access. But, I do want the concrete class to provide read/write access. Is there a way to make this work? Thanks, PaulH Unfortunately, Base can't be changed to an interface as it contains non-abstract functionality also. Something I should have thought to put in the original problem description. public abstract class Base { public abstract DateTime StartTime { get; } public void Buzz() { // do something interesting... } } My solution is to do this: public class Foo : Base { DateTime start_time_; public override DateTime StartTime { get { return start_time_; } } internal void SetStartTime { start_time_ = value; } } It's not as nice as I'd like, but it works.

    Read the article

  • Save Web Articles to Read Later with Instapaper

    - by Mysticgeek
    Have you ever come across a bunch of great articles that you want to read online, but just don’t have the time? Today we take a look at an online service that allows you to read your articles later, either online, or on an iPhone, or eReader. Instapaper Instapaper is an awesome tool that allows you to save web pages so you can read them at a later time. Not only does it save an online article to read later, but also gives you several choices for where you want to read it. Sign up for a free account, and drag the “Read Later” bookmarklet to the bookmarks bar in your browser. To save a page you’ll need to be logged into your account. When you’re at a page that you can’t read right away, just click on the Read Later button in the bookmarks bar. After clicking the Read Later button, a small message is displayed indicating that the page has been saved to the Instapaper site. Save as many pages as you want, and when you’re ready to read them, go to the Instapaper site and you’ll see a list of the articles you saved. You can click on the link to go directly to the saved oage, read it as text (leaving out a bunch of images), or archive the article for later. One of the really appealing beta features is you can save the article in .mobi format for a Kindle, or ePub format for other eReaders such a the Sony Reader. Another neat feature is the “Instapaper Text” bookmarklet that lets you view an article on a graphics heavy page with only text, but doesn’t save it to your account. Before After There are also other cool features such as iPhone Apps, Kindle automatic wireless delivery, send items to Google Reader, and more. If you wish you could collect all of the neat articles you run across each day for reading later via multiple formats, Instapaper is a great tool for the job. Check Out Instapaper Similar Articles Productive Geek Tips Save Pages for Later With Reading List Extension for FirefoxGreat Geek SitesAbout the GeekHow-To Geek Changes in ProgressMake Outlook 2007 Mark Items as Read When Viewed in Reading Pane TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 Classic Cinema Online offers 100’s of OnDemand Movies OutSync will Sync Photos of your Friends on Facebook and Outlook Windows 7 Easter Theme YoWindoW, a real time weather screensaver Optimize your computer the Microsoft way Stormpulse provides slick, real time weather data

    Read the article

  • Linux: Force fsck of a read-only mounted filesystem?

    - by Timothy Miller
    I'm developing for a headless embedded appliance, running CentOS 6.2. The user can connect a keyboard, but not a monitor, and a serial console would require opening the case, something we don't want the user to have to do. This all pretty much obviates the possibility of using a recovery USB drive to boot from, unless all it does is blindly reimage the harddrive. I would like to provide some recovery facilities, and I have written a tool that comes up on /dev/tty1 in place of getty to provide these functions. One such function is fsck. I have found out how to remount the root and other file systems read-only. Now that they are read-only, it should be safe to fsck them and then reboot. Unfortunately, fsck complains to me that the filesystems are mounted and refuses to do anything. How can I force fsck to run on a read-only mounted partition? Based on my research, this is going to have to be something obscure. "-f" just means to force repair of a clean (but unmounted) partition. I need to repair a clean or unclean mounted partition. From what I read, this is something "only experts" should do, but no one has bothered to explain how the experts do it. I'm hoping someone can reveal this to me. BTW, I've noticed that e2fsck 1.42.4 on Gentoo will let you fsck a mounted partition, even mounted read-write, but it seems only to do so if fsck is run from a terminal, so it can ask the user if they're sure they want to do something so dangerous. I'm not sure if the CentOS version does the same thing, but it appears that fsck CAN repair a mounted partition, but it flatly refuses to when not run from a terminal. One last-resort option is for me to compile my own hacked fsck. But I'm afraid I'll mess it up in some unexpected way. Thanks! Note: Originally posted here.

    Read the article

  • can't load/read yahoo geocode as xml and read it in jquery

    - by mastah
    Hi, I tried saving the result as an xml, when I read from there it works, but if I read it from yahoo's api, doesn't load anything. You can check it here here's my script $(document).ready(function(){ $.ajax({ type: "GET", url: "http://local.yahooapis.com/MapsService/V1/geocode?appid=YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--&zip=10035", dataType: "xml", success: function(xml) { $(xml).find('Result').each(function(){ var city = $(this).find('City').text(); var state = $(this).find('State').text(); $('<div />').html('<p>'+city+'</p><p>'+state+'</p>').insertAfter('h2'); }); } }); });

    Read the article

  • pdf read pages to BitmapData in AS3

    - by Hadi
    I’m starting a project in flash AS3 and my objective is to load any pdf file into my flash project and convert all its pages to BitmapData... I am familiar with byteArray and I know I must access the pdf in binary level but I don’t know where to start and how to start. I was hoping if you could give me some insight? Maybe a suggestion to an already library that is doing a similar work? Any idea os appreciated just to get me started...

    Read the article

  • Opennetcf how to read sms messagestore with c#

    - by druffmuff
    I'm currently reading the messagestore with InTheHand, but I want to do this with OpenNetCF. Can someone post any samples? Here is how I do this with InTheHand: foreach (InTheHand.WindowsMobile.PocketOutlook.SmsMessage mess in sess.SmsAccount.SentItems) { if (mess.Received.Year == thisYear && mess.Received.Month == thisMonth) { smsThisMonth++; } }

    Read the article

  • how to read character from console in c++?

    - by tsubasa
    I'm struggling with reading characters from console in c++. Here is what I tried to do: char x; char y; char z; cout<<"Please enter your string: "; string s; getline(cin,s); istringstream is(s); is>> x >> y >> z; The problem is if the user enter something like this "1 20 100": x will get 1 y will get 2 z will get 0 What I want to get is x = 1; y = 20; z = 100; Anybody has suggestions?

    Read the article

  • C child read giving "resource temporarily unavailable"

    - by Gary
    So I have a file stream from a parent process to a child - and most of the time it works fine. However, when reading from it multiple times quickly, using fgets() will return NULL and the error is set to "resource temporarily unavailable". The problem is intermittent - and running the script that does the reads will sometimes have fgets return NULL and sometimes wont. Could anyone help me stop this error from happening? Thanks!

    Read the article

  • Read/Write Excel Files Directly To/From Memory

    - by Corey O.
    Several people have asked, in a roundabout way, but I have yet to see a workable solution. Is there any way to open an excel file from directly memory (like a byte[]) ? Likewise is there a way to write a file directly to memory? I am looking for solutions that will not involve the hard disk or juggling temporary files. Thanks in advance for any suggestions.

    Read the article

  • Why doesn't `stdin.read()` read entire buffer?

    - by Shookie
    I've got the following code: def get_input(self): """ Reads command from stdin, returns its JSON form """ json_string = sys.stdin.read() print("json string is: "+json_string) json_data =json.loads(json_string) return json_data It reads a json string that was sent to it from another process. The json is read from stdin. For some reason I get the following output: json string is: <Some json here> json string is: Traceback (most recent call last): File "/Users/Matan/Documents/workspace/ProjectSH/addonmanager/addon_manager.py", line 63, in <module> manager.accept_commands() File "/Users/Matan/Documents/workspace/ProjectSH/addonmanager/addon_manager.py", line 49, in accept_commands json_data = self.get_input() File "/Users/Matan/Documents/workspace/ProjectSH/addonmanager/addon_manager.py", line 42, in get_input json_data =json.loads(json_string) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode raise ValueError("No JSON object could be decoded") So for some reason it reads an empty string from stdin instead of reading only the json. I've checked, and the code that writes to this process's stdin writes to it only once. What's wrong here?

    Read the article

  • Trying to read FormsAuthentication tickets to read in other areas of site

    - by Pasha Aryana
    Hi, NOTE: I have included 3 links in here to my localhost areas but could not submit the post so I seperetaed them with a space character so it would post on stackoverflow. I currently have 2 ASP.NET MVC apps in my solution. First I run the first one by setting it to be startup project. It goes to the login page, from there once the data has been entered I execute the following code: var authTicket = new FormsAuthenticationTicket(1, login.LoginDataContract.MSISDN, DateTime.Now, DateTime.Now.AddMinutes(Convert.ToDouble("30")), true, ""); string cookieContents = FormsAuthentication.Encrypt(authTicket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents) { Expires = authTicket.Expiration, //Path = FormsAuthentication.FormsCookiePath //Path = "http://localhost" Domain = "" }; if (System.Web.HttpContext.Current != null) { System.Web.HttpContext.Current.Response.Cookies.Add(cookie); } As you can see I have set the Domain = "", so theoretically speaking it should work on any thing under my http: //localhost. Then I have set the persist security of the cookie to true so I can access it from any where under localhost. The cookie writes fine and I get logged in and all godd for now. BTW the url for this login page is: http //localhost/MyAccount/Login Now then I stop the solution and set the other MVC apps to be the startup. Then I run it. The URL for the second site is: http: //localhost/WebActivations/ Here is the code in the other apps start controller: public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; // PASHA: Added code to read the authorization cookie set at // login in MyAccount *.sln for (int i = 0; i < System.Web.HttpContext.Current.Request.Cookies.Count;i++) { Response.Write(System.Web.HttpContext.Current.Request.Cookies[i].Name + " " + System.Web.HttpContext.Current.Request.Cookies[i].Value); } HttpCookie authorizationCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName.ToString()]; // decrypt. FormsAuthenticationTicket authorizationForm = FormsAuthentication.Decrypt(authorizationCookie.Value); ViewData["Message"] = authorizationForm.UserData[0].ToString(); return View(); } public ActionResult About() { return View(); } The problem is in this Home controller when I run the solution it cannot read the authentication cookie, you see the loop there it does not find the .ASPXAUTH cookie. But once it crashes in Firefox I have a look in the Page Info and then security and Cookies and its there and its the same cookie. What am I doing wrong?

    Read the article

  • How can I read a comma delimited text file in a Windows batch file?

    - by Sms
    I can get it to read the text file until it becomes a comma delimited text file. I would like to read the two variables on each line and test each one with a If statement for another condition. Problem is I can't read the variables properly. Tried many things but here is what I will post. Timeouts are to see what's happening: for /f "tokens=*" %%a in (TestText.txt) do ( timeout /t 1 echo %%a is the present variabe timeout /t 2 if %%a=="One","1" echo Match for "One","1" timeout /t 3 if %%a=="One""1" echo Match for "One","1" timeout /t 4 if %%a=="One" echo Match for "One" timeout /t 5 if %%a=="1" echo Match for "1" timeout /t 6 ) TestText.txt "One","1" "Two","2" "Three","3" "Four","4" OUTPUT: "One","1" is the present variabe

    Read the article

  • How to mount a HFS partition in Ubuntu as Read/Write?

    - by GiH
    I plugged in my external harddrive (which was formatted on my Mac into HFS+ journaled) to my Ubuntu desktop 9.04 64bit. I am not able to get the drive to mount with write capability, how do I do that? Right now all I'm getting is read access, I tried sudo mount -t hfsplus /dev/sdf2 /media/"Portable HD" but that still gave me only read access... ideas??

    Read the article

  • How to edit a read-only document in LibreOffice?

    - by TestUser16418
    I need to fill a form (which I received in .doc format and saved as .odt). The file is read-only except for the fields where I can enter the information. Unfortunately, with the fields filled it doesn't fit on one page, and I need to edit it so I can print and submit it. With LibreOffice beta 3, I could edit anything outside of the fields, and the fonts were slightly smaller, so it fit on the page even with the fields filled. Today I upgraded LibreOffice, and when I opened to edit a field where I had a mistake, it no longer fits on the page, and I can't edit it. When I opened the properties it says that the document is NOT read-only, but it is. When I try to delete text it tells me that I can't edit the read-only content. Can anyone give me some advice, because I've been trying to print my form for 2 hours already. I tried AbiWord and KWord, but both are missing elements from the page (though the forms fit). I can also edit the margins (Format - Page is dimmed, but when I begin to edit a field it's no longer dimmed)med

    Read the article

  • C#/.NET Little Wonders: Interlocked Read() and Exchange()

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Last time we discussed the Interlocked class and its Add(), Increment(), and Decrement() methods which are all useful for updating a value atomically by adding (or subtracting).  However, this begs the question of how do we set and read those values atomically as well? Read() – Read a value atomically Let’s begin by examining the following code: 1: public class Incrementor 2: { 3: private long _value = 0; 4:  5: public long Value { get { return _value; } } 6:  7: public void Increment() 8: { 9: Interlocked.Increment(ref _value); 10: } 11: } 12:  It uses an interlocked increment, as we discuss in my previous post (here), so we know that the increment will be thread-safe.  But, to realize what’s potentially wrong we have to know a bit about how atomic reads are in 32 bit and 64 bit .NET environments. When you are dealing with an item smaller or equal to the system word size (such as an int on a 32 bit system or a long on a 64 bit system) then the read is generally atomic, because it can grab all of the bits needed at once.  However, when dealing with something larger than the system word size (reading a long on a 32 bit system for example), it cannot grab the whole value at once, which can lead to some problems since this read isn’t atomic. For example, this means that on a 32 bit system we may read one half of the long before another thread increments the value, and the other half of it after the increment.  To protect us from reading an invalid value in this manner, we can do an Interlocked.Read() to force the read to be atomic (of course, you’d want to make sure any writes or increments are atomic also): 1: public class Incrementor 2: { 3: private long _value = 0; 4:  5: public long Value 6: { 7: get { return Interlocked.Read(ref _value); } 8: } 9:  10: public void Increment() 11: { 12: Interlocked.Increment(ref _value); 13: } 14: } Now we are guaranteed that we will read the 64 bit value atomically on a 32 bit system, thus ensuring our thread safety (assuming all other reads, writes, increments, etc. are likewise protected).  Note that as stated before, and according to the MSDN (here), it isn’t strictly necessary to use Interlocked.Read() for reading 64 bit values on 64 bit systems, but for those still working in 32 bit environments, it comes in handy when dealing with long atomically. Exchange() – Exchanges two values atomically Exchange() lets us store a new value in the given location (the ref parameter) and return the old value as a result. So just as Read() allows us to read atomically, one use of Exchange() is to write values atomically.  For example, if we wanted to add a Reset() method to our Incrementor, we could do something like this: 1: public void Reset() 2: { 3: _value = 0; 4: } But the assignment wouldn’t be atomic on 32 bit systems, since the word size is 32 bits and the variable is a long (64 bits).  Thus our assignment could have only set half the value when a threaded read or increment happens, which would put us in a bad state. So instead, we could write Reset() like this: 1: public void Reset() 2: { 3: Interlocked.Exchange(ref _value, 0); 4: } And we’d be safe again on a 32 bit system. But this isn’t the only reason Exchange() is valuable.  The key comes in realizing that Exchange() doesn’t just set a new value, it returns the old as well in an atomic step.  Hence the name “exchange”: you are swapping the value to set with the stored value. So why would we want to do this?  Well, anytime you want to set a value and take action based on the previous value.  An example of this might be a scheme where you have several tasks, and during every so often, each of the tasks may nominate themselves to do some administrative chore.  Perhaps you don’t want to make this thread dedicated for whatever reason, but want to be robust enough to let any of the threads that isn’t currently occupied nominate itself for the job.  An easy and lightweight way to do this would be to have a long representing whether someone has acquired the “election” or not.  So a 0 would indicate no one has been elected and 1 would indicate someone has been elected. We could then base our nomination strategy as follows: every so often, a thread will attempt an Interlocked.Exchange() on the long and with a value of 1.  The first thread to do so will set it to a 1 and return back the old value of 0.  We can use this to show that they were the first to nominate and be chosen are thus “in charge”.  Anyone who nominates after that will attempt the same Exchange() but will get back a value of 1, which indicates that someone already had set it to a 1 before them, thus they are not elected. Then, the only other step we need take is to remember to release the election flag once the elected thread accomplishes its task, which we’d do by setting the value back to 0.  In this way, the next thread to nominate with Exchange() will get back the 0 letting them know they are the new elected nominee. Such code might look like this: 1: public class Nominator 2: { 3: private long _nomination = 0; 4: public bool Elect() 5: { 6: return Interlocked.Exchange(ref _nomination, 1) == 0; 7: } 8: public bool Release() 9: { 10: return Interlocked.Exchange(ref _nomination, 0) == 1; 11: } 12: } There’s many ways to do this, of course, but you get the idea.  Running 5 threads doing some “sleep” work might look like this: 1: var nominator = new Nominator(); 2: var random = new Random(); 3: Parallel.For(0, 5, i => 4: { 5:  6: for (int j = 0; j < _iterations; ++j) 7: { 8: if (nominator.Elect()) 9: { 10: // elected 11: Console.WriteLine("Elected nominee " + i); 12: Thread.Sleep(random.Next(100, 5000)); 13: nominator.Release(); 14: } 15: else 16: { 17: // not elected 18: Console.WriteLine("Did not elect nominee " + i); 19: } 20: // sleep before check again 21: Thread.Sleep(1000); 22: } 23: }); And would spit out results like: 1: Elected nominee 0 2: Did not elect nominee 2 3: Did not elect nominee 1 4: Did not elect nominee 4 5: Did not elect nominee 3 6: Did not elect nominee 3 7: Did not elect nominee 1 8: Did not elect nominee 2 9: Did not elect nominee 4 10: Elected nominee 3 11: Did not elect nominee 2 12: Did not elect nominee 1 13: Did not elect nominee 4 14: Elected nominee 0 15: Did not elect nominee 2 16: Did not elect nominee 4 17: ... Another nice thing about the Interlocked.Exchange() is it can be used to thread-safely set pretty much anything 64 bits or less in size including references, pointers (in unsafe mode), floats, doubles, etc.  Summary So, now we’ve seen two more things we can do with Interlocked: reading and exchanging a value atomically.  Read() and Exchange() are especially valuable for reading/writing 64 bit values atomically in a 32 bit system.  Exchange() has value even beyond simply atomic writes by using the Exchange() to your advantage, since it reads and set the value atomically, which allows you to do lightweight nomination systems. There’s still a few more goodies in the Interlocked class which we’ll explore next time! Technorati Tags: C#,CSharp,.NET,Little Wonders,Interlocked

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >