c# - FileStream Cannot Access File Because It is Being Used by Another Process -
i have looked @ number of different posts, including the process cannot access file because being used process, ioexception: process cannot access file 'file path' because being used process, , better way of invoking thread , logging text file in c#
i might missing simple, reason cannot figure out how safely write file in async method. making call web api, , when response comes in, want write file. code follows:
static class program { private static object locker = new object(); static void main() { string line; streamreader reader = new streamreader(@"..\..\source.tsv"); int counter = 0; while((line = reader.readline()) != null) { if(++counter % 100 == 0) { console.writeline(counter); } string response = makerequest(line.trim()).result; if(response.length == 0) { continue; } lock(locker) { using (filestream sourcestream = new filestream("destination.tsv", filemode.append, fileaccess.write, fileshare.none, buffersize: 4096, useasync: false)) { byte[] encodedtext = encoding.unicode.getbytes(line.trim() + "\t" + response + "\n"); sourcestream.write(encodedtext, 0, encodedtext.length); } } } console.writeline("all done, hit enter exit...."); console.readline(); } static async task<string> makerequest(string querystring) { var client = new httpclient(); //web api call string response = getwebresponse(); return response; } }
i thought lock(locker) make access "destination.tsv" mutually exclusive, , never have multiple processes trying write file @ same time. have tried other lock variations, such readerwriterlock, readerwriterlockslim, none of them have helped me guarantee mutual exclusion. makes me think isn't problem of locking, then, somehow not dropping filestream correctly every time. thought
using(filestream ...
syntax ensure never leave thread file open though, stuck on throwing error.
how supposed writing in async method?
edit: removed api call, , when writing file simple string, "the process cannot access file because being used process" when include thread.sleep() call in main, haven't been able repro when take sleep call out. web api access reasons, though, need sleep main thread.
edit 2: following advice jim, tried rewrite return task instead of void async call. still, end access error in main thread. i'm confused because 1 main thread, , because waiting makerequest response, shouldn't there ever 1 thread running?
Comments
Post a Comment