Is .NET double.ToString threadsafe?

I'm seeing an issue in a production ASP.NET application that involves the following code, which is used to render the geocoordinates of a particular object:

private double _longitude;
private double _latitude;

public string ToCsvString()
{
    return _latitude + "," + _longitude;
}

Thread.CurrentThread.CurrentCulture will be set to different values based on the incoming request. The behavior I'm seeing is that the result of this function will vary independent of the threadlocal culture. At times the decimal points and commas are incorrect for the current culture. More strangely, it seems that once set wrong, the wrong value persists.

Does ToString on double cache values?


It shouldn't cache the values, especially because of the culture issue you mentioned. Two things come to mind:

  • How/where do you set the culture? Perhaps there is a bug there?
  • Are you sure it is THIS place that creates the bug? Perhaps the culture is different than you think? Perhaps the results of this function are cached elsewhere in your code?

  • 为什么不使用显式的ToString方法来让你手动指定一个区域性的IFormatProvider?


    For rendering geocoordinates, I suggest that you best define your own fixed formatting or culture rather than leaving it for the framework, default culture setting or culture info of the running thread.

    I would do it like this to format it to 4 decimal points:

    return _latitude.ToString("0.0000") + "," + _longitude.ToString("0.0000");
    

    or

    string.Format("{0:0.0000}, "{1:0.0000}", _latitude, _longitude);
    

    Or if you want the decimal separator to be culture specific,

    CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-AU");
    return _latitude.ToString("N4", ci) + "," + _longitude.ToString("N4", ci);
    
    链接地址: http://www.djcxy.com/p/75092.html

    上一篇: 在Silverlight应用程序中进行文化

    下一篇: .NET double.ToString线程安全吗?