How should I use static method/classes within async/await operations?How would I run an async Task<T> method synchronously?How to call asynchronous method from synchronous method in C#?Creating an async method in .NET 4.0 that can be used with “await” in .NET 4.5async/await - when to return a Task vs void?Using async/await for multiple tasksWhen should i use async/await and when not?How and when to use ‘async’ and ‘await’Async and Await - How is order of execution maintained?What is the difference between asynchronous programming and multithreading?Using async/await with a forEach loop

if i accidentally leaked my schools ip address and someone d doses my school am i at fault

"Estrontium" on poster

Lorentz invariance of Maxwell's equations in matter

How long can fsck take on a 30 TB volume?

Are on’yomi words loanwords?

Is it a good idea to copy a trader when investing?

What's the difference between "ricochet" and "bounce"?

Do Monks gain the 9th level Unarmored Movement benefit when wearing armor or using a shield?

Can a planet still function with a damaged moon?

Narcissistic cube asks who are we?

Add Columns to .csv from Multiple Files

Unicode-math and mathrm result in missing symbols

How is Arya still alive?

Why was Sam Wilson chosen for this, but not Bucky?

Company stopped paying my salary. What are my options?

Metric of positive curvature and Homology group

Has there been evidence of any other gods?

Program for finding longest run of zeros from a list of 100 random integers which are either 0 or 1

My perfect evil overlord plan... or is it?

Are double contractions formal? Eg: "couldn't've" for "could not have"

When do you stop "pushing" a book?

What can cause an unfrozen indoor copper drain pipe to crack?

Was there a contingency plan in place if Little Boy failed to detonate?

Pre-1993 comic in which Wolverine's claws were turned to rubber?



How should I use static method/classes within async/await operations?


How would I run an async Task<T> method synchronously?How to call asynchronous method from synchronous method in C#?Creating an async method in .NET 4.0 that can be used with “await” in .NET 4.5async/await - when to return a Task vs void?Using async/await for multiple tasksWhen should i use async/await and when not?How and when to use ‘async’ and ‘await’Async and Await - How is order of execution maintained?What is the difference between asynchronous programming and multithreading?Using async/await with a forEach loop






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








24















It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.



Now async/await has been introduced into the c# 4.5+ framework - which simplifies multithreaded applications and encourages responsive UI.



However - as a lock cannot/should not be placed over an awaiting method (and I'm not debating that) does that now make static methods utilizing async/await completely redundant?










share|improve this question






















  • Calling a static method from multiple threads will be fine if it doesn't have any side-effects.

    – Adam Houldsworth
    Oct 24 '12 at 9:15












  • If a method has side-effects then it shouldn't be static in the first place, since it violates the guideline that global mutable state should be avoided.

    – CodesInChaos
    Oct 24 '12 at 9:17












  • @CodesInChaos I don't think you can violate guidelines ;-) Either way, the point I was trying to make is that locking won't be required for most static methods, unless some sort of shared state is being mutated. The OP hasn't provided enough information on that front, and seems to imply locking because it is static, not locking for state management.

    – Adam Houldsworth
    Oct 24 '12 at 9:21


















24















It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.



Now async/await has been introduced into the c# 4.5+ framework - which simplifies multithreaded applications and encourages responsive UI.



However - as a lock cannot/should not be placed over an awaiting method (and I'm not debating that) does that now make static methods utilizing async/await completely redundant?










share|improve this question






















  • Calling a static method from multiple threads will be fine if it doesn't have any side-effects.

    – Adam Houldsworth
    Oct 24 '12 at 9:15












  • If a method has side-effects then it shouldn't be static in the first place, since it violates the guideline that global mutable state should be avoided.

    – CodesInChaos
    Oct 24 '12 at 9:17












  • @CodesInChaos I don't think you can violate guidelines ;-) Either way, the point I was trying to make is that locking won't be required for most static methods, unless some sort of shared state is being mutated. The OP hasn't provided enough information on that front, and seems to imply locking because it is static, not locking for state management.

    – Adam Houldsworth
    Oct 24 '12 at 9:21














24












24








24


5






It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.



Now async/await has been introduced into the c# 4.5+ framework - which simplifies multithreaded applications and encourages responsive UI.



However - as a lock cannot/should not be placed over an awaiting method (and I'm not debating that) does that now make static methods utilizing async/await completely redundant?










share|improve this question














It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.



Now async/await has been introduced into the c# 4.5+ framework - which simplifies multithreaded applications and encourages responsive UI.



However - as a lock cannot/should not be placed over an awaiting method (and I'm not debating that) does that now make static methods utilizing async/await completely redundant?







c# asynchronous async-await






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Oct 24 '12 at 9:13









Patrick McCurleyPatrick McCurley

1,0011823




1,0011823












  • Calling a static method from multiple threads will be fine if it doesn't have any side-effects.

    – Adam Houldsworth
    Oct 24 '12 at 9:15












  • If a method has side-effects then it shouldn't be static in the first place, since it violates the guideline that global mutable state should be avoided.

    – CodesInChaos
    Oct 24 '12 at 9:17












  • @CodesInChaos I don't think you can violate guidelines ;-) Either way, the point I was trying to make is that locking won't be required for most static methods, unless some sort of shared state is being mutated. The OP hasn't provided enough information on that front, and seems to imply locking because it is static, not locking for state management.

    – Adam Houldsworth
    Oct 24 '12 at 9:21


















  • Calling a static method from multiple threads will be fine if it doesn't have any side-effects.

    – Adam Houldsworth
    Oct 24 '12 at 9:15












  • If a method has side-effects then it shouldn't be static in the first place, since it violates the guideline that global mutable state should be avoided.

    – CodesInChaos
    Oct 24 '12 at 9:17












  • @CodesInChaos I don't think you can violate guidelines ;-) Either way, the point I was trying to make is that locking won't be required for most static methods, unless some sort of shared state is being mutated. The OP hasn't provided enough information on that front, and seems to imply locking because it is static, not locking for state management.

    – Adam Houldsworth
    Oct 24 '12 at 9:21

















Calling a static method from multiple threads will be fine if it doesn't have any side-effects.

– Adam Houldsworth
Oct 24 '12 at 9:15






Calling a static method from multiple threads will be fine if it doesn't have any side-effects.

– Adam Houldsworth
Oct 24 '12 at 9:15














If a method has side-effects then it shouldn't be static in the first place, since it violates the guideline that global mutable state should be avoided.

– CodesInChaos
Oct 24 '12 at 9:17






If a method has side-effects then it shouldn't be static in the first place, since it violates the guideline that global mutable state should be avoided.

– CodesInChaos
Oct 24 '12 at 9:17














@CodesInChaos I don't think you can violate guidelines ;-) Either way, the point I was trying to make is that locking won't be required for most static methods, unless some sort of shared state is being mutated. The OP hasn't provided enough information on that front, and seems to imply locking because it is static, not locking for state management.

– Adam Houldsworth
Oct 24 '12 at 9:21






@CodesInChaos I don't think you can violate guidelines ;-) Either way, the point I was trying to make is that locking won't be required for most static methods, unless some sort of shared state is being mutated. The OP hasn't provided enough information on that front, and seems to imply locking because it is static, not locking for state management.

– Adam Houldsworth
Oct 24 '12 at 9:21













1 Answer
1






active

oldest

votes


















41















It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.




Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:



public static async Task<int> GetPageLength(string url)

string text = await new WebClient().DownloadStringTaskAsync(url);
return text.Length;



If you do have shared state - or if you're in an instance method on an instance which is used by multiple threads - you need to work out how you would ideally want your asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.






share|improve this answer























  • Apologies - i do actually mean static methods with shared state - will update my question to provide an example

    – Patrick McCurley
    Oct 24 '12 at 9:37






  • 2





    @PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

    – Jon Skeet
    Oct 24 '12 at 9:41






  • 1





    Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

    – Patrick McCurley
    Oct 24 '12 at 9:47






  • 9





    @PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

    – Jon Skeet
    Oct 24 '12 at 10:00












  • @PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

    – Jon Skeet
    Oct 24 '12 at 10:08











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13046174%2fhow-should-i-use-static-method-classes-within-async-await-operations%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









41















It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.




Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:



public static async Task<int> GetPageLength(string url)

string text = await new WebClient().DownloadStringTaskAsync(url);
return text.Length;



If you do have shared state - or if you're in an instance method on an instance which is used by multiple threads - you need to work out how you would ideally want your asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.






share|improve this answer























  • Apologies - i do actually mean static methods with shared state - will update my question to provide an example

    – Patrick McCurley
    Oct 24 '12 at 9:37






  • 2





    @PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

    – Jon Skeet
    Oct 24 '12 at 9:41






  • 1





    Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

    – Patrick McCurley
    Oct 24 '12 at 9:47






  • 9





    @PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

    – Jon Skeet
    Oct 24 '12 at 10:00












  • @PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

    – Jon Skeet
    Oct 24 '12 at 10:08















41















It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.




Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:



public static async Task<int> GetPageLength(string url)

string text = await new WebClient().DownloadStringTaskAsync(url);
return text.Length;



If you do have shared state - or if you're in an instance method on an instance which is used by multiple threads - you need to work out how you would ideally want your asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.






share|improve this answer























  • Apologies - i do actually mean static methods with shared state - will update my question to provide an example

    – Patrick McCurley
    Oct 24 '12 at 9:37






  • 2





    @PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

    – Jon Skeet
    Oct 24 '12 at 9:41






  • 1





    Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

    – Patrick McCurley
    Oct 24 '12 at 9:47






  • 9





    @PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

    – Jon Skeet
    Oct 24 '12 at 10:00












  • @PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

    – Jon Skeet
    Oct 24 '12 at 10:08













41












41








41








It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.




Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:



public static async Task<int> GetPageLength(string url)

string text = await new WebClient().DownloadStringTaskAsync(url);
return text.Length;



If you do have shared state - or if you're in an instance method on an instance which is used by multiple threads - you need to work out how you would ideally want your asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.






share|improve this answer














It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.




Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:



public static async Task<int> GetPageLength(string url)

string text = await new WebClient().DownloadStringTaskAsync(url);
return text.Length;



If you do have shared state - or if you're in an instance method on an instance which is used by multiple threads - you need to work out how you would ideally want your asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.







share|improve this answer












share|improve this answer



share|improve this answer










answered Oct 24 '12 at 9:16









Jon SkeetJon Skeet

1104k70380378500




1104k70380378500












  • Apologies - i do actually mean static methods with shared state - will update my question to provide an example

    – Patrick McCurley
    Oct 24 '12 at 9:37






  • 2





    @PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

    – Jon Skeet
    Oct 24 '12 at 9:41






  • 1





    Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

    – Patrick McCurley
    Oct 24 '12 at 9:47






  • 9





    @PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

    – Jon Skeet
    Oct 24 '12 at 10:00












  • @PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

    – Jon Skeet
    Oct 24 '12 at 10:08

















  • Apologies - i do actually mean static methods with shared state - will update my question to provide an example

    – Patrick McCurley
    Oct 24 '12 at 9:37






  • 2





    @PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

    – Jon Skeet
    Oct 24 '12 at 9:41






  • 1





    Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

    – Patrick McCurley
    Oct 24 '12 at 9:47






  • 9





    @PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

    – Jon Skeet
    Oct 24 '12 at 10:00












  • @PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

    – Jon Skeet
    Oct 24 '12 at 10:08
















Apologies - i do actually mean static methods with shared state - will update my question to provide an example

– Patrick McCurley
Oct 24 '12 at 9:37





Apologies - i do actually mean static methods with shared state - will update my question to provide an example

– Patrick McCurley
Oct 24 '12 at 9:37




2




2





@PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

– Jon Skeet
Oct 24 '12 at 9:41





@PatrickMcCurley: In that case it's not so much the "staticness" that the problem - it's the "multiple threads wanting to use the same shared state". That can occur just as easily in instance members, when the instances are shared across states.

– Jon Skeet
Oct 24 '12 at 9:41




1




1





Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

– Patrick McCurley
Oct 24 '12 at 9:47





Actually having thought about your original answer I am starting to doubt my understanding of what happens when a static method is called. If a local variable is declared in a static method, and 2 threads enter the static method at the same time - could that not lead to race conditions for the locally declared object?

– Patrick McCurley
Oct 24 '12 at 9:47




9




9





@PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

– Jon Skeet
Oct 24 '12 at 10:00






@PatrickMcCurley: No, absolutely not. The two static method invocations are entirely separate. (Assuming the two local variables don't actually obtain references to the same objects, e.g. via a singleton)

– Jon Skeet
Oct 24 '12 at 10:00














@PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

– Jon Skeet
Oct 24 '12 at 10:08





@PatrickMcCurley: Note that this is true for non-static methods too - local variables are independent for separate invocations. Otherwise recursive calls in particular would be very hard!

– Jon Skeet
Oct 24 '12 at 10:08



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13046174%2fhow-should-i-use-static-method-classes-within-async-await-operations%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해