1

对于我的 Web 服务课程,我正在尝试创建一个非常简单的登录系统。我遇到了一个问题,即每当调用 checkCredentials 时 createAccounts() 会不断获得无限次。知道为什么吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;

public class Service : IService
{
    static String path = @"PATH REMOVED";
    List<Account> accounts = new List<Account>();
    StreamWriter sw = null;

    private void createAccounts()
    {
        String data = File.ReadAllText(path);
        string[] data2 = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        string[] temp;
        for (int i = 0; i < data2.Length; i++)
        {
            temp = data2[i].Split(',');
            if(!usernameExists(temp[0]) && temp[0] != "")
            {
                accounts.Add(new Account(temp[0],temp[1]));
            }
        }
    }

    public bool CreateAccount(String username, String password)
    {
        createAccounts();
        sw = File.AppendText(path);
        if (!usernameExists(username))
        {
            sw.WriteLine(username + "," + password + "\n");
            sw.Close();
            sw = null;
            return true;
        }
        else
        {
            sw.Close();
            sw = null;
            return false;
        }
    }

    public bool usernameExists(String username)
    {
        createAccounts();
        if(accounts.Exists(a => a.username == username))
            return true;
        else
            return false;
    }

    public bool CheckCredentials(String username, String password)
    {
        createAccounts();
        if (usernameExists(username))
        {
            if(accounts.Find(a => a.username == username).username == username && accounts.Find(a => a.username == username).password == password)
                return true;
            else
                return false;
        }
        else
            return false;

    }

}

class Account
{
    public String username;
    public String password;

    public Account(String u, String p)
    {
        username = u;
        password = p;
    }

}
4

2 回答 2

1

你把数据保存在一个文件中,你不应该无限次写入。当你频繁请求时,它会在多线程中写入文件,一个线程会锁定文件。我建议您使用 try...catch...write 文件来查找问题:

    public bool CreateAccount(String username, String password)
    {
        createAccounts();

        try
        {
            sw = File.AppendText(path);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        if (!usernameExists(username))
        {
            sw.WriteLine(username + "," + password + "\n");
            sw.Close();
            sw = null;
            return true;
        }
        else
        {
            sw.Close();
            sw = null;
            return false;
        }
    }
于 2012-10-27T03:33:47.500 回答
1

在 createAccounts 和 usernameExists 之间有一个循环。只要 data2.Length 不为零,您就会无休止地循环。

于 2012-10-27T04:17:53.330 回答